需求:
1.有5個學生,每個學生有三門功課
2.從鍵盤輸入以上資料(姓名,三門課成績)
3.輸入格式為:zhangshan,30,40,60並計算出總成績
4.把學生資訊和計算出來的總成績按從低到高的順序進行儲存 思路:
1.先建立一個學生對象,實現比較子,讓學生對象自身具備比較性,同時要複寫hashcode()和equeas()方法
2.建立鍵盤錄入,同時建立TreeSet集合,將鍵盤錄入的資料存入集合
3.將集合中的資料存入到檔案中
import java.io.*;import java.util.*;class StudentInfoTest{public static void main(String[] args) throws IOException{//自訂比較子Comparator<Student> cmp=Collections.reverseOrder();Set<Student> treeset=StudentInfoTool.getStudentInfo(cmp);StudentInfoTool.writeToFile(treeset);}}//建立學生對象class Student implements Comparable<Student>{private String name;private int cn;private int ma;private int en;private int sum;Student(String name,int cn,int ma,int en){this.name=name;this.cn=cn;this.ma=ma;this.en=en;sum=cn+ma+en;}public String getName(){return name;}public int getSum(){return sum;}//複寫hashCode方法public int hashCode(){return this.name.hashCode()+sum*6;}//複寫equals方法public boolean equals(Object obj){if(obj instanceof Student)throw new ClassCastException("類型不符。");Student str=(Student)obj;return this.name.equals(str.getName()) && this.sum==str.getSum();}public int compareTo(Student s){int num=new Integer(this.sum).compareTo(new Integer(s.sum));if(num==0)return this.name.compareTo(s.name);return num;}public String toString(){return "["+name+", "+cn+", "+ma+", "+en+"]";}}//建立操作學生的工具類class StudentInfoTool{//空比較子public static Set<Student> getStudentInfo() throws IOException{return StudentInfoTool.getStudentInfo(null);}public static Set<Student> getStudentInfo(Comparator<Student> cmp) throws IOException{//鍵盤錄入BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));//建立TreeSet集合,cmp為自訂比較子Set<Student> treeset=new TreeSet<Student>(cmp);String line=null;while((line=bufr.readLine())!=null){if("over".equals(line))break;//通過","對學生資訊進行切割String[] info=line.split(",");Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));treeset.add(stu);}bufr.close();System.out.println(treeset);return treeset;}//存入檔案方法public static void writeToFile(Set<Student> stu) throws IOException{//檔案寫入流BufferedWriter bufw=new BufferedWriter(new FileWriter("studentInfo.txt"));//從集合裡取出學生資訊for(Student s : stu){bufw.write(s.toString()+"\t");bufw.write(s.getSum()+"");bufw.newLine();bufw.flush();}bufw.close();}}