public class TreeSet1 {
public static void main(String[] args) {
// 键盘输入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)按照总分高低排序
//创建学生类Student
Scanner sc = new Scanner(System.in);
System.out.println("请按照格式输入字符");
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getSum()-s1.getSum();
return num==0 ? 1:num;
}
});
while(ts.size()<5) {//TreeSet长度为5
String line = sc.nextLine();
String[] arr = line.split(",");//用,切割字符返回一个字符数组
int chinese = Integer.parseInt(arr[1]);
int math = Integer.parseInt(arr[2]);
int english = Integer.parseInt(arr[3]);
ts.add(new Student(arr[0],chinese,math,english));
}
System.out.println("个人信息排名为:");
for (Student s :ts) {
System.out.println(s);
}
}
}
--------------------------------------------------------------
Student类
package com.heima03;
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;
}
@Override
public String toString() {//重写toString()
return name+","+chinese+","+math+","+english;
}
}
package com.heima03;
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;
}
@Override
public String toString() {//重写toString()
return name+","+chinese+","+math+","+english;
}