需求:
定義學生類,每個學生有3門課的成績,
從鍵盤輸入以上數據(包括姓名,三門課成績),
輸入的格式:如:zhagnsan,30,40,60計算出總成績,
並把學生的信息和計算出的總分數高低順序存放在磁盤文件"stud.txt"中。
步奏:
1,描述學生對象。
2,定義一個可操作學生對象的工具類。
思路:
1,鍵盤錄入一行數據,將該行數據封裝成學生對象
2,學生對象需要存儲,用到集合,對學生進行總分排序,可使用TreeSet
3,將集合中的信息寫入到一個文件中
實現過程:
import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int cn,ma,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 int getSum(){ //獲取學生總分
return sum;
}
public String toString(){ //獲取學生信息
return "student["+name+" 語文:"+cn+" 數學:"+ma+" 英語:"+en+" 總分:"+sum+"]";
}
public int hashCode(){ //複寫hashSet集合的hashCode()方法
return name.hashCode()+sum*22;
}
public boolean equals(Object obj){ //複寫TreeSet集合的equals方法
if(!(obj instanceof Student)) //健壯性判斷
throw new ClassCastException("請輸入學生的信息!");
Student s = (Student)obj; //轉型
return this.name.equals(s.name) && this.sum==s.sum;
}
public int compareTo(Student s){ //覆蓋compareTo方法
int num = new Integer(this.sum).compareTo(new Integer(s.sum));//要將int型包裝成對象才能使用CompareTo()方法
if(num==0)
return this.name.compareTo(s.name); //如果總分相同,按照姓名排序
return num;
}
}
class StudentInfoTool //獲取信息
{
public static Set<Student> getStudents() throws IOException
{
return getStudents(null); //不帶比較器的集合
} //帶比較器的集合
public static Set<Student> getStudents(Comparator<Student> comp) throws IOException
{
System.out.println("請按照指定的格式錄入成績:學生姓名,語文,數學,英語");
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Student> stu = null;
if(comp==null)
stu = new TreeSet<Student>(); //不帶比較器的集合,使用Student類內部compareTo()
else
stu = new TreeSet<Student>(comp);//帶比較器的集合
while ((line=bufr.readLine()) !=null)
{
if("over".equals(line))
break; //輸入over時退出程序
String[] info = line.split(",");//將讀取的字符在","切割成字符數組
Student s = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));
//String轉int
stu.add(s); //往集合中添加元素
}
bufr.close(); //關閉資源
return stu;
}
public static void writeToFile(Set<Student> stu) throws IOException
{
BufferedWriter bufw = new BufferedWriter(new FileWriter("studentsInfo.txt"));//創建文檔存儲信息
for(Student s:stu) //遍歷集合
{
bufw.write(s.toString());//將集合中對象轉成字符串寫入文檔
bufw.newLine(); //換行
bufw.flush(); //刷新流
}
bufw.close();//關閉流
}
}
class StudentInfoTest
{
public static void main(String[] args) throws IOException
{
Comparator<Student> comp = Collections.reverseOrder();//反轉比較器
Set<Student> stu = StudentInfoTool.getStudents(comp);//獲取Student對象集合
StudentInfoTool.writeToFile(stu); //將集合中數據寫入到文檔中
}
}