標籤:tree int scan 構造 比較 引用 示範 顯示 案例
/**
-
- 需求:鍵盤錄入5個學生資訊(姓名,語文成績,數學成績,英語成績),按照總分從高到低輸出到控制台。
- <p>
- 分析:
- 1,定義一個學生類
- 成員變數:姓名,語文成績,數學成績,英語成績,總成績
- 成員方法:空參,有參構造,有參構造的參數分別是姓名,語文成績,數學成績,英語成績
- toString方法,在遍曆集合中的Student對象列印對象引用的時候會顯示內容值
- 2,鍵盤錄入需要Scanner,建立鍵盤錄入對象
- 3,建立TreeSet集合對象,在TreeSet的建構函式中傳入比較子,按照總分比較
- 4,錄入五個學生,所以以集合中的學生個數為判斷條件,如果size是小於5就進行儲存
- 5,將錄入的字串切割,用逗號切割,會返回一個字串數組,將字串數組中從二個元素轉換成int數,
- 6,將轉換後的結果封裝成Student對象,將Student添加到TreeSet集合中
7,遍曆TreeSet集合列印每一個Student對象**/
public void anli() {
//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 chiness = 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], chiness, math, english));}//7,遍曆TreeSet集合列印每一個Student對象System.out.println("排序後的學生資訊:");for (Student t : ts) { System.out.println(t);}
}```
TreeSet學習案例