请帮我写一个存储全班45人的姓名和数学成绩并按照数学成绩降序排列用java编程
import java.util.*;
public class Student { private String name; private int mathScore;
public Student(String name, int mathScore) {
this.name = name;
this.mathScore = mathScore;
}
public String getName() {
return name;
}
public int getMathScore() {
return mathScore;
}
}
public class Main {
public static void main(String[] args) {
List
// 添加45个学生
studentList.add(new Student("张三", 90));
studentList.add(new Student("李四", 85));
studentList.add(new Student("王五", 95));
// ... 还有42个学生
// 按照数学成绩降序排列
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s2.getMathScore() - s1.getMathScore();
}
});
// 输出排序结果
for (int i = 0; i < studentList.size(); i++) {
System.out.println("第" + (i + 1) + "名:" + studentList.get(i).getName() + ",数学成绩:" + studentList.get(i).getMathScore());
}
}
}
原文地址: http://www.cveoy.top/t/topic/b4Pt 著作权归作者所有。请勿转载和采集!