题目:牛客网
解题思路:
输入有2个属性,分别是用户名和成绩
1、定义一个class Student ,包含两个属性,分别是name和score
2、定义一个list,其元素是Student类,按照输入的内容将用户添加到list中
3、使用Collections容器进行排序,因为要按照score属性进行排序,需要提供Comparator
package offer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
class Student{
public String name;
public int score;
public Student(String name , int score){
this.name = name;
this.score = score;
}
}
public class Main {
public static void sortStudent(int flag, ArrayList<Student> stulist){
//引入Comparator,指定比较的算法
if(flag == 1){
Comparator<Student> c = new Comparator<Student>() {
@Override
//compare函数返回值大于0则交换o1和o2,小于0则不交换
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.score-o2.score;
}
};
Collections.sort(stulist, c);
}
else{
Comparator<Student> c = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o2.score-o1.score;
}
};
Collections.sort(stulist, c);
}
for(int i = 0; i < stulist.size(); i++){
System.out.printf("%s %d%n", stulist.get(i).name, stulist.get(i).score);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int num = in.nextInt();
int flag = in.nextInt();
ArrayList<Student> stulist = new ArrayList<Student>();
for(int i = 0; i < num; i++){
String stuName = in.next();
int stuScore = in.nextInt();
stulist.add(new Student(stuName , stuScore));
}
sortStudent(flag, stulist);
}
}
}