需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台。

    1. Scanner sc = new Scanner(System.in);
    2. System.out.println("请输入5个学生成绩格式是:(姓名,语文成绩,数学成绩,英语成绩)");
    3. TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
    4. @Override
    5. public int compare(Student s1, Student s2) {
    6. int num = s2.getSum() - s1.getSum(); //根据学生的总成绩降序排列
    7. return num == 0 ? 1 : num;
    8. }
    9. });
    10. while(ts.size() < 5) {
    11. String line = sc.nextLine();
    12. try {
    13. String[] arr = line.split(",");
    14. int chinese = Integer.parseInt(arr[1]); //转换语文成绩
    15. int math = Integer.parseInt(arr[2]); //转换数学成绩
    16. int english = Integer.parseInt(arr[3]); //转换英语成绩
    17. ts.add(new Student(arr[0], chinese, math, english));
    18. } catch (Exception e) {
    19. System.out.println("录入格式有误,输入5个学生成绩格式是:(姓名,语文成绩,数学成绩,英语成绩");
    20. }
    21. }
    22. System.out.println("排序后的学生成绩是:");
    23. for (Student s : ts) {
    24. System.out.println(s);
    25. }