題目描述
查找和排序 題目:輸入任意(用戶,成績)序列,能夠得到成績從高到低或從低到高的排列,相同成績
都按先錄入排列在前的規則處理。
例示:
jack 70
peter 96
Tom 70
smith 67
從高到低 成績
peter 96
jack 70
Tom 70
smith 67
從低到高
smith 67
Tom 70
jack 70
peter 96
輸入描述
輸入多行,先輸入要排序的人的個數,而後分別輸入他們的名字和成績,以一個空格隔開
用戶名字,字符串,非空串,長度不超過20;
成績,整數,範圍【0,100】
輸入排序方式,0或1,0表示成績從高到低方式輸出名字和成績,1表示成績從低到高方式輸出名字和成績
輸出描述
按照指定方式輸出名字和成績,名字和成績之間以一個空格隔開
輸入例子
3 0 fang 90 yang 50 ning 70
輸出例子
fang 90 ning 70 yang 50
算法實現
import java.util.*;
/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
int n = scanner.nextInt();
int t = scanner.nextInt();
Student[] students = new Student[n];
for (int i = 0; i < n; i++) {
String name = scanner.next().trim();
int score = scanner.nextInt();
students[i] = new Student(name, score);
}
sort(t, students);
StringBuilder builder = new StringBuilder();
for (Student s : students) {
builder.append(s.name).append(" ").append(s.score).append('\n');
}
System.out.print(builder.toString());
}
scanner.close();
}
private static void sort(int t, Main.Student[] students) {
if (t == 1) {
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Main.Student s, Main.Student t) {
return s.score - t.score;
}
});
} else if (t == 0) {
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Main.Student s, Main.Student t) {
return t.score - s.score;
}
});
}
}
private static class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
}
}