package hashset;
public class Student {
private String name;
private int chinese;
private int math;
private int english;
private int sum;
public Student() {
super();
}
public Student(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
this.sum=this.chinese+this.math+this.english;
}
public int getSum() {
return sum;
}
public String toString(){
return name+","+chinese+","+math+","+english+","+sum;
}
}
package hashset;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class Demo5 {
/*
* 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台。
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生信息");
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {// 一定要注意此处!!!
@Override
public int compare(Student c1, Student c2) {// 重写此方法
int num = c2.getSum() - c1.getSum();// c2表示已经在集合中的学生,c1表示即将要进入集合中的学生,倒序的话,在集合中的成绩减去即将进入集合中的成绩
return num == 0 ? 1 : num;//如果等于等于零的话表示成绩一样不会再添加到集合中,所以一定要写一个正数大于零
}
});
while (ts.size() < 5) {
String s = sc.nextLine();// 因为输入的字符串,必须切割成字符数组,便于数据的操作!
String arr[] = s.split(",");
Integer chinese = Integer.parseInt(arr[1]);// 注意强制类型的转换
Integer math = Integer.parseInt(arr[2]);
Integer english = Integer.parseInt(arr[3]);
ts.add(new Student(arr[0], chinese, math, english));// 将Studen封装成对象传入集合中
}
for (Student s : ts) {
System.out.println(s);
}
}
}
|
|