【java編程】IO流和集合類綜合題目__編程

來源:互聯網
上載者:User
需求:

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();}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.