用java定义学生类(学号、姓名、成绩).用列表list存放班级学生信息.然后按照成绩排序,并输出学生信息
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/22 00:53:43
用java定义学生类(学号、姓名、成绩).用列表list存放班级学生信息.然后按照成绩排序,并输出学生信息
用java定义学生类(学号、姓名、成绩).用列表list存放班级学生信息.然后按照成绩排序,并输出学生信息
用java定义学生类(学号、姓名、成绩).用列表list存放班级学生信息.然后按照成绩排序,并输出学生信息
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Admin {
public static void main(String... args) {
List data = new ArrayList();
Student s0 = new Student();
s0.setNo("000");
s0.setName("a");
s0.setChengji(100.0);
data.add(s0);
Student s1 = new Student();
s1.setNo("001");
s1.setName("b");
s1.setChengji(99.0);
data.add(s1);
Student s2 = new Student();
s2.setNo("002");
s2.setName("c");
s2.setChengji(98.0);
data.add(s2);
System.out.println("排序前");
show(data);
System.out.println("排序后");
sort(data);
show(data);
}
private static void sort(List data) {
Collections.sort(data, new Comparator() {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return (int) (s1.getChengji() - s2.getChengji());
}
});
}
private static void show(List data) {
for (int i = 0; i < data.size(); i++) {
System.out.println(data.get(i));
}
}
}
class Student {
private String no;
private String name;
private double chengji;
public double getChengji() {
return chengji;
}
public void setChengji(double chengji) {
this.chengji = chengji;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String toString() {
return "学号:" + no + ",姓名:" + name + ",成绩:" + chengji;
}
}
结果
排序前
学号:000,姓名:a,成绩:100.0
学号:001,姓名:b,成绩:99.0
学号:002,姓名:c,成绩:98.0
排序后
学号:002,姓名:c,成绩:98.0
学号:001,姓名:b,成绩:99.0
学号:000,姓名:a,成绩:100.0