按成绩排序
// 排序算法
Arrays.sort(students, new Comparator<Student>(){
@Override
public int compare(Student stu1, Student stu2) {
if (comp == 1) {
if (stu1.score > stu2.score) return 1;
if (stu1.score < stu2.score) return -1;
return 0;
} else {
if (stu1.score < stu2.score) return 1;
if (stu1.score > stu2.score) return -1;
return 0;
}
}
});
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int comp = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (scanner.hasNextLine()) { // 注意 while 处理多个 case
int count = Integer.parseInt(scanner.nextLine());
int comp = Integer.parseInt(scanner.nextLine());
Student[] students = new Student[count];
for (int i = 0; i < count; i++) {
String[] temp = scanner.nextLine().split(" ");
students[i] = new Student(temp[0], Integer.parseInt(temp[1]));
}
Arrays.sort(students, new Comparator<Student>(){
@Override
public int compare(Student stu1, Student stu2) {
if (comp == 1) {
if (stu1.score > stu2.score) return 1;
if (stu1.score < stu2.score) return -1;
return 0;
} else {
if (stu1.score < stu2.score) return 1;
if (stu1.score > stu2.score) return -1;
return 0;
}
}
});
for (Student student : students) {
System.out.println(student.name + " " + student.score);
}
}
}
public static class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
}
}