get,set方法
public class Student {
private String name;
private Integer chinese;
private Integer math;
private Integer english;
//编写一个求每个学生总分的方法
public int sum(){
return chinese+math+english;
}
public Student() {
super();
}
public Student(String name, Integer chinese, Integer math, Integer english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getChinese() {
return chinese;
}
public void setChinese(Integer chinese) {
this.chinese = chinese;
}
public Integer getMath() {
return math;
}
public void setMath(Integer math) {
this.math = math;
}
public Integer getEnglish() {
return english;
}
public void setEnglish(Integer english) {
this.english = english;
}
}
for循环手动输入学生成绩
public class StudentTest {
public static void main(String[] args) {
//使用treeset集合装学生
TreeSet<Student> treeset = new TreeSet<>(new Studentcompare());
//录入学生信息
for (int i = 0; i <3; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名");
String name = sc.nextLine();
System.out.println("请输入语文成绩");
String chinese = sc.nextLine();
System.out.println("请输入数学成绩");
String math = sc.nextLine();
System.out.println("请输入英语成绩");
String english = sc.nextLine();
Student student = new Student(name, Integer.parseInt(chinese), Integer.parseInt(math), Integer.parseInt(english));
treeset.add(student);
}
//打印学生信息
for (Student stu : treeset) {
System.out.println("姓名:"+stu.getName()+""+"总分:"+stu.sum());
}
}
}
/*
*
* 指定学生比较器的规则
* 1.以总分进行排序
* 2.总分相等以语文成绩排序
* 3.语文成绩相等以数学成绩排序
* 4.数学成绩相等以英语成绩排序
* 5.英语成绩相等以姓名排序
*
* */
public class Studentcompare implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
int sum1= o2.sum()-o1.sum();
int sum2=sum1==0?o2.getChinese()-o2.getChinese():sum1;
int sum3=sum2==0?o2.getMath()-o1.getMath():sum2;
int sum4=sum3==0?o2.getEnglish()-o1.getEnglish():sum3;
int sum5=sum4==0?o2.getName().compareTo(o1.getName()):sum4;
return sum5;
}
}