1. 程式人生 > >【TreeSet:鍵盤錄入5個學生信息,按照總分從高到低輸出到控制臺】

【TreeSet:鍵盤錄入5個學生信息,按照總分從高到低輸出到控制臺】

package parseint compareto div rri sheng == nes etc

package com.yjf.esupplier.common.test;

import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

/**
 * @author shusheng
 * @description 鍵盤錄入5個學生信息,按照總分從高到低輸出到控制臺
 * @Email [email protected]
 * @date 2018/12/17 15:36
 */
public class TreeSetDemo3 {

    public static void main(String[] args) {

        
// 創建一個TreeSet集合 TreeSet<Student3> ts = new TreeSet<Student3>(new Comparator<Student3>() { @Override public int compare(Student3 s1, Student3 s2) { // 總分從高到低 int num = s2.getSum() - s1.getSum(); // 總分相同的不一定語文相同
int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num; // 總分相同的不一定數序相同 int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2; // 總分相同的不一定英語相同 int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
// 姓名還不一定相同呢 int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName()) : num4; return num5; } }); System.out.println("學生信息錄入開始"); // 鍵盤錄入5個學生信息 for (int x = 1; x <= 5; x++) { Scanner sc = new Scanner(System.in); System.out.println("請輸入第" + x + "個學生的姓名:"); String name = sc.nextLine(); System.out.println("請輸入第" + x + "個學生的語文成績:"); String chineseString = sc.nextLine(); System.out.println("請輸入第" + x + "個學生的數學成績:"); String mathString = sc.nextLine(); System.out.println("請輸入第" + x + "個學生的英語成績:"); String englishString = sc.nextLine(); // 把數據封裝到學生對象中 Student3 s = new Student3(); s.setName(name); s.setChinese(Integer.parseInt(chineseString)); s.setMath(Integer.parseInt(mathString)); s.setEnglish(Integer.parseInt(englishString)); // 把學生對象添加到集合 ts.add(s); } System.out.println("學習信息從高到低排序如下:"); System.out.println("姓名\t語文成績\t數學成績\t英語成績"); // 遍歷集合 for (Student3 s : ts) { System.out.println(s.getName() + "\t" + s.getChinese() + "\t" + s.getMath() + "\t" + s.getEnglish()); } } } class Student3 { // 姓名 private String name; // 語文成績 private int chinese; // 數學成績 private int math; // 英語成績 private int english; public Student3(String name, int chinese, int math, int english) { super(); this.name = name; this.chinese = chinese; this.math = math; this.english = english; } public Student3() { super(); } 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; } }

【TreeSet:鍵盤錄入5個學生信息,按照總分從高到低輸出到控制臺】