本帖最后由 张向辉 于 2013-1-30 11:48 编辑
- import java.io.*;
- import java.util.*;
- class getStudentInfoDemo
- {
- public static void main(String[] args)
- {
- Comparator<Student> cmp = Collections.reverseOrder();
- Set<Student> stus = infoTool.getStudentSet(cmp);
- File f = new File("r:\\1.txt");
- infoTool.writeInfo(stus,f);
-
- }
- }
- class Student implements Comparable<Student>//学生类
- {
- private String name;
- private int cn,ma,en;
- private int sum;
- Student(String name, int cn, int ma,int en)
- {
- this.name = name;
- this.cn = cn ;
- this.ma = ma ;
- this.en = en ;
- getSum() ;
- }
-
- public String getName()
- {
- return name;
- }
- public int getSum()
- {
- return sum = cn + ma + en ;
- }
- public String toString()
- {
- return "学生:{\t"+name+",\t语文"+cn+",\t数学"+ma+",\t英语"+en+"\t}"+"总分"+sum;
- }
-
- public int hashCode()
- {
- return name.hashCode()+sum*17;
- }
-
- 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;
- }
- }
- class infoTool//工具类
- {
- public static Set<Student> getStudentSet(Comparator<Student> cmp)//获取集合的
- {
- System.out.println("请输入学生的姓名和语文,数学,英语成绩,例如(张三,60,60,60)");
- BufferedReader buffr = null;
- Set<Student> stuSet = new TreeSet<Student>(cmp);
- try
- {
- buffr = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- while((line=buffr.readLine())!=null)
- {
- if(line.equals("over"))
- break;
- String[] arr = line.split(",");
- Student stu = new Student(arr[0],Integer.parseInt(arr[1]),Integer.parseInt(arr[2]),Integer.parseInt(arr[3]));
- stuSet.add(stu);
- }
- return stuSet;
- }
- catch (IOException e)
- {
- throw new RuntimeException("输入信息失败");
- }
- finally
- {
- try
- {
- if(buffr!=null)
- buffr.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("关闭失败");
- }
- }
- }
- public static void writeInfo(Set<Student> s , File f)//写入文件的
- {
- BufferedWriter buffw = null;
- try
- { buffw = new BufferedWriter(new FileWriter(f));
- for(Student stu : s)
- {
-
- buffw.write(stu.toString());
- buffw.newLine();
- buffw.flush();
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("输出信息失败");
- }
- finally
- {
- try
- {
- if(buffw!=null)
- buffw.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("关闭失败");
- }
- }
- }
- }
- //就连续按了2下回车就出异常的了 功能是能正常的....
复制代码 |
|