package com.loaderman.test; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; import com.heiam.bean.Student; public class Test { /** * * A:案例演示 * 需求:鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績),按照總分從高到低輸出到控制台。 * * 分析: * 1,定義一個學生類 * 成員變量:姓名,語文成績,數學成績,英語成績,總成績 * 成員方法:空參,有參構造,有參構造的參數分別是姓名,語文成績,數學成績,英語成績 * toString方法,在遍歷集合中的Student對象打印對象引用的時候會顯示屬性值 * 2,鍵盤錄入需要Scanner,創建鍵盤錄入對象 * 3,創建TreeSet集合對象,在TreeSet的構造函數中傳入比較器,按照總分比較 * 4,錄入五個學生,所以以集合中的學生個數為判斷條件,如果size是小於5就進行存儲 * 5,將錄入的字符串切割,用逗號切割,會返回一個字符串數組,將字符串數組中從二個元素轉換成int數, * 6,將轉換后的結果封裝成Student對象,將Student添加到TreeSet集合中 * 7,遍歷TreeSet集合打印每一個Student對象 */ public static void main(String[] args) { //2,鍵盤錄入需要Scanner,創建鍵盤錄入對象 Scanner sc = new Scanner(System.in); System.out.println("請輸入學生成績格式是:姓名,語文成績,數學成績,英語成績"); //3,創建TreeSet集合對象,在TreeSet的構造函數中傳入比較器,按照總分比較 TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int num = s2.getSum() - s1.getSum(); return num == 0 ? 1 : num; } }); //4,錄入五個學生,所以以集合中的學生個數為判斷條件,如果size是小於5就進行存儲 while(ts.size() < 5) { //5,將錄入的字符串切割,用逗號切割,會返回一個字符串數組,將字符串數組中從二個元素轉換成int數, String line = sc.nextLine(); String[] arr = line.split(","); int chinese = Integer.parseInt(arr[1]); int math = Integer.parseInt(arr[2]); int english = Integer.parseInt(arr[3]); //6,將轉換后的結果封裝成Student對象,將Student添加到TreeSet集合中 ts.add(new Student(arr[0], chinese, math, english)); } //7,遍歷TreeSet集合打印每一個Student對象 System.out.println("排序后的學生信息:"); for (Student s : ts) { System.out.println(s); } } }