要求:
描述一個學生類,學生類包含學生姓名,數學成績,語文成績,英語成績等屬性,從鍵盤輸入學生對象,然後將輸入的學生對象存入文件,按照總分的大小從大到小排序。
import java.io.*;
import java.util.*;
//描述學生類
class Student implements Comparable<Student>
{
private String name;
private int math;
private int china;
private int english;
private int sum;
public Student(String name, int math, int china, int english){
this.name = name;
this.math = math;
this.china = china;
this.english = english;
sum = math + china + english;
}
//實現Comparable接口,實現改方法
public int compareTo(Student s){
int num = Integer.valueOf(this.sum).compareTo(Integer.valueOf(s.sum));
if(num == 0){
return this.name.compareTo(s.name);
}
return num;
}
public String toString(){
return this.name + " : [" + this.math + "," + this.china + "," + this.english + "]";
}
public int getSum(){
return this.sum;
}
}
class StudentUtil
{
private static Set<Student> s;
public StudentUtil(Set<Student> s){
this.s = s;
}
//以“姓名,數學成績,語文成績,英語成績”的形式從鍵盤存入數據
public static void getStudent() throws Exception{
BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while((str = bis.readLine()) != null){
if(str.equals("over")){
break;
}
String[] info = str.split(",");
Student student = new Student(info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2]), Integer.parseInt(info[3]));
s.add(student);
}
bis.close();
}
//將集合中數據寫入文件
public void writeStudent() throws Exception{
BufferedWriter bw = new BufferedWriter(new FileWriter("StuInfo.txt"));
Iterator iterator = s.iterator();
while(iterator.hasNext()){
Student s = (Student)iterator.next();
bw.write(s.toString() + "\t");
bw.write(s.getSum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
class StudentDemo
{
public static void main(String[] args) throws Exception
{
//獲得從逆向排序的比較器
Comparator<Student> c = Collections.reverseOrder();
StudentUtil su = new StudentUtil(new TreeSet<Student>(c));
su.getStudent();
System.out.println("獲取成功!");
su.writeStudent();
System.out.println("寫入成功!");
}
}