package cn.itcast_08;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
/*
* 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到底输出到控制台
*
* 分析:
* A:定义学生类
* B:创建TreeSet集合
* C:总分从高到低如何实现呢?
* D:键盘录入5个学生信息
* E:遍历TreeSet集合
*/
public class TreeSetDemo {
public static void main(String[] args) {
// 创建TreeSet集合
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
public int compare(Student s1, Student s2) {
// 按照总分从高到底
int sum = s2.getSum() - s1.getSum();
// 总分相同不一定是语文相同
int sum2 = sum == 0 ? s1.getChinese() - s2.getChinese() : sum;
// 总分相同不一定是数学相同
int sum3 = sum2 == 0 ? s1.getMath() - s2.getMath() : sum2;
// 总分相同不一定是英语相同
int sum4 = sum3 == 0 ? s1.getEnglish() - s2.getEnglish() : sum3;
// 姓名还不一定相同
int sum5 = sum4 == 0 ? s1.getName().compareTo(s2.getName())
: sum4;
return sum5;
}
});
System.out.println("学生信息录入开始\n");
// 键盘录入5个学生信息
int count = 1;
while (count <= 5) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第" + count + "个学生姓名:");
String name = sc.nextLine();
System.out.print("请输入第" + count + "学生语文成绩:");
String chineseString = sc.nextLine();
System.out.print("请输入第" + count + "学生数学成绩:");
String mathString = sc.nextLine();
System.out.print("请输入第" + count + "学生英语成绩:");
String englishString = sc.nextLine();
// 把数据封装到学生对象中
Student stu = new Student();
stu.setName(name);
stu.setChinese(Integer.parseInt(chineseString));
stu.setMath(Integer.parseInt(mathString));
stu.setEnglish(Integer.parseInt(englishString));
// 把学生对象添加到集合对象中
ts.add(stu);
count++;
}
System.out.println("学生信息录入完毕");
System.out.println("学生信息从高到低排序如下:");
// 遍历TreeSet集合
System.out.println("姓名\t语文成绩\t数学成绩\t英语成绩");
for (Student s : ts) {
System.out.println(s.getName() + "\t" + s.getChinese() + "\t"
+ s.getMath() + "\t" + s.getEnglish());
}
}
}
package cn.itcast_08;
public class Student {
/**
* 姓名
*/
private String name;
/**
* 语文成绩
*/
private int chinese;
/**
* 数学成绩
*/
private int math;
/**
* 英语成绩
*/
private int english;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int chinese, int math, int english) {
super();
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 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;
}
public int getSum() {
return this.chinese + this.math + this.english;
}
}