import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int shuxue,yuwen,yingyu;
private int sum;
Student(String name,int shuxue,int yuwen,int yingyu )
{
this.name=name;
this.shuxue=shuxue;
this.yuwen=yuwen;
this.yingyu=yingyu;
sum=shuxue+yuwen+yingyu;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
public int hashCode()
{
return name.hashCode()+sum*78;
}
public boolean equals(Object obj)
{
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)
{
int num =new Integer(this.sum).compareTo(new Integer (s.sum));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public String toString()
{
return "student["+name+","+shuxue+","+yuwen+","+yingyu+"]";
}
}
class StudentInfoTool
{
public static Set<Student>getStudents()throws IOException
{
return getStudents(null);
}
public static Set<Student>getStudents(Comparator<Student> cmp)throws IOException//方法,返回集合
{
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));//读取键盘
String line=null;
Set<Student>stus=null;
if (cmp==null)
stus=new TreeSet<Student>();
else
stus=new TreeSet<Student>(cmp);//进行比较创建TreeSet集合
while((line=bufr.readLine())!=null)
{
if("over".equals(line))
break;
String []info=line.split(",");//信息之间用逗号隔开
Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));//把学生信息封装成对象并放到集合里面,就要创建集合
stus.add(stu);
}
bufr.close();
return stus;
}
public static void write2File(Set<Student> stus)throws IOException
{
BufferedWriter bufw=new BufferedWriter(new FileWriter("stuinfo.txt"));
for(Student stu :stus)
{
bufw.write(stu.toString()+"\t");//"\t"为什么这个地方识别不了啊
bufw.write(stu.getSum()+"");//加一个“”这个 就能了啊 ,高手指点啊?????
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}
class StudentInfo
{
public static void main(String[] args) throws IOException
{
Comparator<Student> cmp=Collections.reverseOrder();//反转比较器
Set<Student>stus=StudentInfoTool.getStudents(cmp);
StudentInfoTool.write2File(stus);
System.out.println("Hello World!");
}
}
/*
我的结果怎么是这种格式啊??高手指点
student[zhaoliu,85,71,89] 245
student[zhouqi,87,45,92] 224
student[zhangsan,92,80,50] 222
student[wanwu,45,85,79] 209
student[lisi,45,54,54] 153
*/ |