(95)鍵盤輸入學生資訊,存入檔案
阿新 • • 發佈:2018-12-25
有5個學生,每個學生有三門課程,從鍵盤輸入以上資料(包括姓名、三門課成績)輸入格式:如zhangsan,30,40,50計算出總成績,並將學生的資訊和計算出的總分數從高到底存放在磁碟檔案“stu.txt”
1,描述學生物件
2,定義一個可以操作學生物件的工具類
思想:
1,通過獲取鍵盤錄入一行資料,並將該行中的資訊取出封裝成學生物件
2,因為你學生有很多,那麼就需要儲存,使用集合,因為要對學生的總分數進行排序,所以可以用用TreeSet
3,將集合的資訊寫入到檔案
//學生類
public class Student implements Comparable<Student> {
private String name;
private int chinGrade;
private int mathGrade;
private int engGrade;
private int sumGrade;
Student(String name,int chinGrade,int mathGrade,int engGrade ){
this.name=name;
this.chinGrade=chinGrade;
this.mathGrade=mathGrade;
this .engGrade=engGrade;
sumGrade= chinGrade+mathGrade+ engGrade;
}
//可能被二叉樹使用
public int compareTo(Student stu) {
if(this.sumGrade>stu.sumGrade)
return -1;
if(this.sumGrade==stu.sumGrade)
return this.name.compareTo(stu.name);
return 1 ;
}
public int getSumGrade() {
return sumGrade;
}
public String getName() {
return name;
}
//可能被雜湊用到
public int hashCode() {
return name.hashCode()+sumGrade*85;
}
public boolean equals(Object obj) {
if(!(obj instanceof Student ))
throw new ClassCastException();
Student stu=(Student)obj;
return this.getName().equals(stu.getName())&&this.sumGrade==stu.sumGrade;
}
public String toString() {
return "姓名:"+name+" 語文:"+chinGrade+" 數學:"+mathGrade+" 英語"+engGrade+" 總分:"+sumGrade;
}
}
//
import java.io.*;
import java.util.*;
public class StuDemo {
public static TreeSet<Student> getStudents() throws IOException{
return getStudents(null);
}
public static TreeSet<Student> getStudents(Comparator<Student> cmp) throws IOException//將資料寫入集合
{
TreeSet<Student> ts=null;
if(cmp==null)
ts=new TreeSet<Student>();
else
ts=new TreeSet<Student>(cmp);
int count=1;
while(count<=5)
{
System.out.println("請輸入第"+count+"名學生的資訊");
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=bufr.readLine();
String[] every=line.split(",");
//將鍵盤輸入的資料封裝成物件
ts.add(new Student(every[0],Integer.parseInt(every[1]),Integer.parseInt(every[2]),Integer.parseInt(every[3])));
count++;
}
return ts;
}
public static void write2File(TreeSet<Student> ts)throws IOException//將集合中的資料寫入檔案
{
//將集合中的資料寫入檔案中
FileWriter fos=new FileWriter("E:\\grade.txt");//因為要用到一行一行的寫,所以用Writer
BufferedWriter bufw=new BufferedWriter(fos);
bufw.write("學生成績以及排名如下:");
bufw.newLine();
Iterator<Student> it=ts.iterator();
while(it.hasNext()) {
Student stu=it.next();
bufw.write(stu.toString());
bufw.newLine();
bufw.flush();
}
bufw.close();
}
public static void main(String[] args)throws IOException {
//Comparator<Student> cmp=Collections.reverseOrder(new MyComp());
//TreeSet ts=getStudents(cmp);//用比較器比較
TreeSet ts=getStudents();//用compareTo比較
write2File(ts);
}
}
//升序比較器
public class MyComp implements Comparator<Student>{
public int compare(Student stu1,Student stu2){
if(stu1.getSumGrade()>stu2.getSumGrade())
return 1;
if(stu1.getSumGrade()>stu2.getSumGrade())
return stu1.getName().compareTo(stu2.getName());
return -1;
}
}