程序从用户
获取名称和位置值以字符串数组存储
根据位置降序显示名称值
public class Samp
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String name[]=new String[5];
System.out.println("enter the name");
for(int i=0;i<name.length;i++)
{
name[i]=sc.nextLine();
}
String location[]=new String[5];
System.out.println("enter the location");
for(int i=0;i<location.length;i++)
{
location[i]=sc.nextLine();
}
//want to sort name with respect to location in descending order
System.out.println("Name and location:");
System.out.println(name[0]+" "+location[0]);
System.out.println(name[1]+" "+location[1]);
System.out.println(name[2]+" "+location[2]);
System.out.println(name[3]+" "+location[3]);
System.out.println(name[4]+" "+location[4]);
}
}
答案 0 :(得分:0)
用户Arrays.Sort();
public class Test{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name[]=new String[5];
System.out.println("enter the name");
for(int i=0;i<name.length;i++)
{
name[i]=sc.nextLine();
}
String location[]=new String[5];
System.out.println("enter the location");
for(int i=0;i<location.length;i++)
{
location[i]=sc.nextLine();
}
Arrays.sort(location); // asc
Arrays.sort(location,Collections.reverseOrder()); //desc
System.out.println("Name and location:");
System.out.println(name[0]+" "+location[0]);
System.out.println(name[1]+" "+location[1]);
System.out.println(name[2]+" "+location[2]);
System.out.println(name[3]+" "+location[3]);
System.out.println(name[4]+" "+location[4]);
}
}
使用比较器排序对象:
class Book {
String name;
String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public static int compareBooks(Book a , Book b)
{
return a.name.compareTo(b.name);
}
@Override
public String toString() {
return "name : " + name + "\t" + "author : " + author;
}
}
public static void main(String[] args) {
Book[] books = {
new Book("Book 3" , "Author 1"),
new Book("Book 2" , "Author 2"),
new Book("Book 1" , "Author 3"),
new Book("Book 4" , "Author 4")
};
Arrays.sort(books , Book::compareBooks);
Arrays.asList(books).forEach(System.out::println);
}
答案 1 :(得分:0)
public class Test{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name[]=new String[5];
String location[]=new String[5];
for(int i=0;i<name.length;i++)
{
System.out.println("enter the name");
name[i]=sc.nextLine();
System.out.println("enter the location");
location[i]=sc.nextLine();
}
Arrays.sort(location,Collections.reverseOrder()); //desc
System.out.println("Name and location:");
System.out.println(name[0]+" "+location[0]);
System.out.println(name[1]+" "+location[1]);
System.out.println(name[2]+" "+location[2]);
System.out.println(name[3]+" "+location[3]);
System.out.println(name[4]+" "+location[4]);
}
}