题目
键盘录入3个学生信息(姓名, 语文成绩, 数学成绩, 英语成绩), 按照总分从高到低输出到控制台。
分析
既然排序就使用TreeSet,使用比较器来排序
程序代码
//学生类
package com.company.test;
public class Student {
private String name;
private int chineseScore;
private int mathScore;
private int englishScore;
public Student() {
}
public Student(String name, int chineseScore, int mathScore, int englishScore) {
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getTotalScore() {
return englishScore + mathScore + chineseScore;
}
}
package com.company.test;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class MyTest {
public static void main(String[] args) {
//采用比较器排序
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//总分一样不能说明是同一个对象还得比较一下姓名
int num=s1.getTotalScore()-s2.getTotalScore();
int num2=num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
Student student = new Student();
System.out.println("请输入第"+i+"个学生的姓名");
String name = sc.nextLine();
student.setName(name);
System.out.println("请输入语文成绩");
String s = sc.nextLine();
student.setChineseScore(Integer.parseInt(s));
System.out.println("请输入数学成绩");
String math = sc.nextLine();
student.setMathScore(Integer.parseInt(math));
System.out.println("请输入英语成绩成绩");
String english = sc.nextLine();
student.setEnglishScore(Integer.parseInt(english));
//存到集合中去
treeSet.add(student);
}
//遍历集合,打印学生信息
System.out.println("姓名\t 语文成绩 数学成绩 英语成绩 总分");
for (Student student : treeSet) {
System.out.println(student.getName()+"\t\t"+student.getChineseScore()+"\t\t"+student.getMathScore()+"\t\t"+student.getEnglishScore()+"\t\t"+student.getTotalScore());
}
}
}