题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
class Person{
int score;
String name;
Person(String n,int s){
this.name = n;
this.score = s;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
int num = in.nextInt();
int order = in.nextInt();
String t = in.nextLine();
List<Person> list = new ArrayList<>();
for(int i=0;i<num;i++){
String name = in.nextLine();
String[] nameCo = name.split(" ");
list.add(new Person(nameCo[0],Integer.parseInt(nameCo[1])));
}
if(order==1){
list.sort(new Comparator<Person>(){
public int compare(Person a,Person b){
return a.score - b.score;
}
});
}
if(order==0){
list.sort(new Comparator<Person>(){
public int compare(Person a,Person b){
return b.score - a.score;
}
});
}
for(Person p: list){
System.out.println(p.name +" "+p.score);
}
}
}
}
查看9道真题和解析