/*
有五个学生,每个学生有三门课的成绩从键盘输入成绩信息包括姓名
*/
import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int math,chinal,eng,all;
Student(String name,int math,int chinal,int eng)
{
this.name=name;
this.math=math;
this.chinal=chinal;
this.eng=eng;
all=math+chinal+eng;
}
public int hashCode()
{
return name.hashCode()+all*23;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("你输入的不是学生对象");
Student stu=(Student)obj;//强行转换成学生
return this.name.equals(stu.name) &&this.all==stu.all;//比较学生的姓名和总分
}
public int compareTo(Student stu)
{
int num=new Integer(stu.all).compareTo(new Integer(this.all));
if(num==0)//如果成绩相同则比较姓名
return this.name.compareTo(stu.name);
return num;
}
public String getName()
{
return name;
}
public String toString()
{
return "Student"+"["+name+","+math+","+chinal+","+eng+"]";
}
public int getAll()
{
return all;
}
}
class Studentinfo
{
public static Set<Student> getStudent() throws IOException
{
return getStudent(null);
}
//获取学生信息
public static Set<Student> getStudent(Comparator<Student> com) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));//获取键盘输入
Set<Student> set=null;
if(com==null)
set=new TreeSet<Student>();//成绩一个二叉树集合'
else
set=new TreeSet<Student>(com);
String line=null;
while ((line=br.readLine())!=null)
{
if("over".equals(line))
break;
String[] arr=line.split(",");
Student stu=new Student(arr[0],Integer.parseInt(arr[1]),
Integer.parseInt(arr[2]),
Integer.parseInt(arr[3]));
set.add(stu); //将学生类添加到二叉树集合中
}
br.close();
return set;
}
//写入学生信息
public static void writetoinfo(Set<Student> stu)throws IOException
{
BufferedWriter bw=new BufferedWriter(new FileWriter("studeninfo.txt"));//创建一个信息写入目的
for (Student str : stu)
{
bw.write(str.toString()+"\t");//写入学生信息
bw.write(str.getAll()+"");//写入总分
bw.newLine();//换行
bw.flush();
}
bw.close();
}
}
class Studenttestinfo
{
public static void main(String[] args) throws IOException
{
Comparator<Student> c=Collections.reverseOrder();//创建一个比较器
Set<Student> stu=Studentinfo.getStudent(c);//获取学生信息集合
Studentinfo.writetoinfo(stu);//调用写入方法
}
}
|