老师的代码有时可以直接用,但是写的时候要注意啊,不能照搬的:
已经修改的地方:
1,判断字符串相等不能用=,要用equals;
if (line.equals("over"))
break;
2,按总分从高到低排序时你的 compareTo函数写的不对;
public int compareTo(Student s)
{
int num=new Integer(s.sum).compareTo(new Integer(this.sum));
if (num!=0)
return num;
return this.name.compareTo(s.name);
}
修改后可以运行的代码:
- /*
- * 从键盘录入学生数据,包含姓名,语数外,然后根据总分由高到低排序输出到文件内
- */
- import java.io.*;
- import java.util.*;
- class SchoolDemo
- {
- public static void main(String[] args) throws IOException
- {
- TreeSet<Student> ts=new TreeSet<Student>();
- BufferedReader bufr=null;
- BufferedWriter bufw=null;
- File file=new File("D:\\myclass\\5.txt");
-
- bufr=new BufferedReader(new InputStreamReader(System.in));
- bufw=new BufferedWriter(new FileWriter(file));
- String line=null;
- while ((line=bufr.readLine())!=null) //读取一行,以“,”切割,传递给student对象
- {
- if (line.equals("over"))
- break;
- String[] arr=line.split(",");
- Student s=new Student(arr[0],Integer.parseInt(arr[1]),Integer.parseInt(arr[2]),Integer.parseInt(arr[3]));
- ts.add(s);//把student添加到集合
- }
- for (Student s1 : ts) //遍历集合,写入输出流
- {
- bufw.write(s1.toString());
- bufw.newLine();
- }
- bufr.close();
- bufw.close();
- }
- }
- //student类,定义一个具有比较性的类,覆写了方法hashcode(),equals(),compareTo()
- class Student implements Comparable<Student>
- {
- private String name;
- private int ma,cn,en,sum;
- Student(String name,int ma,int cn,int en)
- {
- this.name=name;
- this.ma=ma;
- this.cn=cn;
- this.en=en;
- sum=ma+cn+en;
- }
- void setName(String name)
- {
- this.name=name;
- }
- String getName()
- {
- return name;
- }
-
- //此处省略其他各科成绩的set ,get 方法
-
- public int hashcode()
- {
- return name.hashCode()+sum*100;
- }
- public boolean equals(Object obj)
- {
- if (!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
- Student s=(Student)obj;
- return this.name.equals(s.name);
- }
- public int compareTo(Student s)
- {
- int num=new Integer(s.sum).compareTo(new Integer(this.sum));
- if (num!=0)
- return num;
- return this.name.compareTo(s.name);
- }
- public String toString()
- {
- return "Stuednt:"+" "+name+","+ma+","+cn+","+en+'\t'+sum;
- }
- }
复制代码 程序运行结果:
输入:
01,45,56,67
02,33,44,55
03,77,88,99
04,1,2,3
05,21,22,23
over
输出:
Stuednt: 03,77,88,99 264
Stuednt: 01,45,56,67 168
Stuednt: 02,33,44,55 132
Stuednt: 05,21,22,23 66
Stuednt: 04,1,2,3 6
|