案例之键盘录入学生信息按照总分排序
作者:互联网
package MONA.demo06_treeset;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class Demo04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeSet<Student2> ss = new TreeSet<>( new Comparator<Student2>() {
@Override
public int compare(Student2 o1, Student2 o2) {
//按照总分进行排序
int i1 = o1.getSum()-o2.getSum();//按成绩升序排名
//总分相同,那么按语文成绩升序排序
int i2 = (i1 == 0) ? o1.getChinese() - o2.getChinese() : i1;
//语文成和总分都相同
// 按数学成绩进行排序
int i3 = (i2 == 0) ? o1.getMath() - o2.getMath() : i2;
return i3;
}
});
for (int i = 0; i < 2; i++) {
System.out.println("请输入第" + (i+1)+"个学生的信息");
System.out.println("请输入姓名");
String name = sc.next();
System.out.println("请输入语文成绩");
int chinese = sc.nextInt();
System.out.println("请输入数学成绩");
int math = sc.nextInt();
System.out.println("请输入英语成绩");
int english = sc.nextInt();
//封装对象
Student2 s = new Student2(name, chinese, math, english);
ss.add(s);
}
System.out.println(ss);
}
}
class Student2{
private String name;
private int chinese;//语文成绩
private int math;//数学成绩
private int english;//英语成绩
public Student2(String name, int chinese, int math, int english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
//提供获取总分的方法
public int getSum(){
return chinese + math + english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "Student2{" +
"name='" + name + ''' +
", chinese=" + chinese +
", math=" + math +
", english=" + english +
'}';
}
}
标签:name,chinese,int,键盘,总分,english,录入,public,math 来源: https://blog.csdn.net/m0_67402013/article/details/123579677