题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) {
int num = in.nextInt();
in.nextLine();
int order = in.nextInt();
in.nextLine();
Student[] students = new Student[num];
for (int i = 0; i < num; i++) {
String text = in.nextLine();
String name = text.split(" ")[0];
int score = Integer.parseInt(text.split(" ")[1]);
Student student = new Student(name, score);
students[i] = student;
}
if (order == 1) {
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return Integer.compare(o1.score, o2.score);
}
});
} else {
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return Integer.compare(o2.score, o1.score);
}
});
}
for (Student student : students) {
System.out.println(student.name + " " + student.score);
}
}
}
}
class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
}
查看14道真题和解析