- import java.util.*;
- import java.io.*;
- class Student implements Comparable<Student>
- {
- private String name;//名字
- private int ma,cn,en;//语数英
- private int 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;
- }
-
- 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 getName()//返回名字
- {
- return name;
- }
- public int getSum()//返回成绩总和
- {
- return sum;
- }
- public int hasCode()
- {
- 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 String toString()//返回姓名 各科成绩
- {
- return "student["+name+","+ma+","+cn+","+en+"]";
- }
- }
- class StudentInfoTool
- {
- public static Set<Student> getStudent()throws IOException//用默认比较方法
- {
- return getStudent(null);
- }
- public static Set<Student> getStudent(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);
- while((line=bufr.readLine())!=null)//一次读取一行键盘录入
- {
- if("over".equals(line))//over结束程序
- 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);//将学生信息存入Set集合
- }
- 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");//将集合中返回的学生姓名,各科成绩存到输出流缓冲区 //tab
- bufw.write(stu.getSum()+"");//将总成绩存入输出流缓冲区
- bufw.newLine();//换行
- bufw.flush();//将缓冲区数据刷到文本文件中
- }
- bufw.close();
- }
- }
- class StudentInfoTest
- {
- public static void main(String[] args)throws IOException
- {
- Comparator<Student> cmp = Collections.reverseOrder();//返回一个比较器,该比较器强行逆转Comparable比较对象顺序
- Set<Student> stus = StudentInfoTool.getStudent(cmp);//将学生存入集合中并将集合对象返回
- StudentInfoTool.write2File(stus);
- }
- }
复制代码 为什么我设置的tab键有一两行会不起作用
|
|