成绩排序(查找和排序)
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
示例:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
jack 70
Tom 70
peter 96
代码实现:
import java.util.*;
class student{
String name;
int score;
public student(String name,int score){
this.name=name;
this.score=score;
}
}
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
while(input.hasNext()) {
int n = input.nextInt();//要排序的人的个数
int order=input.nextInt();//排序方式
List<student> list=new ArrayList<>();
for (int i = 0; i < n; i++) {
String name = input.next();
int score=input.nextInt();
list.add(new student(name,score));
}
//降序
if(order==0){
Collections.sort(list, new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
return o2.score-o1.score;
}
});
}
//升序
if(order==1){
Collections.sort(list, new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
return o1.score-o2.score;
}
});
}
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).name+" "+list.get(i).score);
}
}
}
}