需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台。分析:1、创建键盘录入对象;
2、创建TreeSet集合,使用匿名内部类实现Comparator接口,重写compara方法
3、判断集合中元素的个数,向其中添加元素
4、遍历集合
class Demo_TreeSet{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生成绩格式,语文成绩,数学成绩,英语成绩,总成绩");
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>{
public int compara( Student s1,Student s2);
int num = s2.getSum() - s1.getSum();
return num == 0 ? 1 : num;
});
while(ts.size()<5){
String line = sc.nextLine();
String[] arr = line.Split(",");
int chinese = Integer.paserInt(arr[1]);
int math = Integer.paserInt(arr[2]);
int english = Integer.paserInt(arr[3]);
ts.add(new Student(arr[0],chinese,math,english));
}
for(Student : s : ts){
System.out.println(s);
}
}
}
class Student{
private String name;
private int chinses;
private int math;
private int enlish;
public Student() {}
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;
}
}
转载于:https://blog.51cto.com/14314113/2393150