在创建学生信息类,包含学号、姓名、年龄、成绩等信息,同时包含一个打印学生信息的方法,创建8个学生信息并添加到List结构中,并将学生信息打印出来,然后以成绩进行排序,并将排序结果打印出来。
/*代码如下*/
import java.util.*;
public class student {
private String name;
private int id;
private int age;
private float score;
public student(){}
public student(String name,int age,int id,float score){
this.name=name;
this.age=age;
this.id=id;
this.score=score;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getScore() {
return score;
}
public void read(){
System.out.println("姓名:"+name + "学号:"+id +"年龄:"+ age+ "成绩:"+score);
}
public static void main(String[] args){
student s1=new student("张三",18,1,80);
student s2=new student("李四",18,2,88);
student s3=new student("王五",18,3,90);
student s4=new student("赵六",18,4,87);
student s5=new student("郭七",18,5,82);
student s6=new student("刘二",18,6,56);
student s7=new student("查一",18,7,81);
student s8=new student("吴八",18,8,88);
List<student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
list.add(s8);
System.out.println("修改前");
for (student s : list) {
s.read();
}
Collections.sort(list, new Comparator<student>() {
@Override
public int compare(student s1, student s2) {
return Double.compare(s2.getScore(), s1.getScore());
}
});
System.out.println("修改后:");
for (student s : list) {
s.read();
}
}
}
创建了一个名为Student的类,包含学号、姓名、年龄和成绩属性,并提供了打印信息的方法。接着创建了8个Student对象,存储在一个ArrayList中,并打印出初始列表。然后使用Collections.sort对列表按成绩降序排序,并再次打印排序后的学生信息。
4024

被折叠的 条评论
为什么被折叠?



