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