题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
scan.nextLine(); //防止nextInt()后面输入nextLine()出现问题,
ArrayList<Student> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
String[] strs = scan.nextLine().split(" ");
String name = strs[0];
int grade = Integer.parseInt(strs[1]);
list.add(new Student(name,grade));
}
Collections.sort(list,new Comparator<Student>(){
public int compare(Student o1,Student o2) {
if(k == 1) {
return o1.grade - o2.grade;
} else {
return o2.grade - o1.grade;
}
}
});
for(Student s : list) {
System.out.println(s.name + " "+s.grade);
}
}
}
class Student{
public String name;
public int grade;
public Student(String name,int grade){
this.name = name;
this.grade = grade;
}
}
查看6道真题和解析