1.某班级有 40 个学生,学号为 180201-180240,全部参加 Java 集合阶段检测,给出所有同学的成绩(可随机产生,范围为 50-100),请编写程序将本班各位同学成绩从高往低排序打印输出,注:成绩相同时学号较小的优先打印要求:打印的信息包含学号、姓名(姓名统一为“同学 J”[J=10,11,12。。。])和成绩。
- 思路分析:
1.随机产生所有同学的成绩:Math.random();
2.所有同学学号,姓名,成绩存储:ArrayList /TreeSet/PriorityQueue;
3.成绩进行从高到低比较:实现比较器类,Collections.sort();
- 实现:
public class Student {
private int id;
private String name;
private int score;
public Student(int id,String name,int score){
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
public class IOTest01 {
private ArrayList<Student> arrayList = new ArrayList<Student>();
public void save(){
Random random = new Random();
for (int i = 0,j = 10; i <= 40; i++) {
int id = 180201 + i;
String name = "同学" + j++;
int score = random.nextInt(51) + 50;
this.arrayList.add(new Student(id,name,score));
}
}
public void sort(){
Comparator<Student> comparator = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getScore()> o1.getScore() ? 1 : o2.getScore() < o1.getScore() ?
-1 : o1.getId() - o2.getId();
}
};
Collections.sort(arrayList,comparator);
}
public void print(){
Iterator<Student> iterator = this.arrayList.iterator();
while (iterator.hasNext()){
Student value = iterator.next();
System.out.println("学号:"+ value.getId() +"姓名:"