import java.io.*;
import java.util.*;
//需求是:在控制台上输入几个学生的姓名,数学,语文成绩,并计算出总成绩,最后安总成绩从高到低排好存入到文件中。
//问题:在学生工具类中已经用TreeSet对学生对象进行了自动排序,为什么学生类还要继承Compareble呢???????
//建立学生类
class Student implements Comparable<Student>
{
private String name;
private int num;
private int cn;
private int sn;
Student(String name,int cn,int sn)
{
this.name=name;
this.cn=cn;
this.sn=sn;
num=cn+sn;
}
public int getNum()
{
return num;
}
public String toString()
{
return "["+this.name+","+this.cn+","+this.sn+"]";
}
public int hashCode()
{
return name.hashCode()+num*70;
}
public int compareTo(Student s)
{
int nu=new Integer(this.num).compareTo(new Integer(s.num));
if(nu==0)
return this.name.compareTo(s.name);
return nu;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配!");
Student s = (Student)obj;
return this.name.equals(s.name)&&this.num==s.num;
}
}
class studentTool //建立学生工具类。
{
public static Set<Student> Student() throws IOException
{
return studentinfo(null);
}
public static Set<Student> studentinfo(Comparator<Student> cmp)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
Set<Student> st = null;
if(cmp==null)
st = new TreeSet<Student>();
else
st = new TreeSet<Student>(cmp);
while((line=br.readLine())!=null)
{
if("over".equals(line))
break;
else
{
String[] info=line.split(",");
Student s = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]));
st.add(s);
}
}
br.close();
return st;
}
public static void xieru(Set<Student> s)throws IOException
{
BufferedWriter bw = new BufferedWriter(new FileWriter("bbb.txt"));
for(Student s1:s)
{
bw.write(s1.toString()+"\t");
bw.write(s1.getNum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
public class Bl
{
public static void main(String[] args) throws IOException
{
Comparator<Student> cmp = Collections.reverseOrder();
Set<Student> se = studentTool.studentinfo(cmp);
studentTool.xieru(se);
}
}
|