本帖最后由 宋超2356 于 2014-4-16 00:04 编辑
- import java.io.*;
- import java.util.*;
- public class TestIo {
- public static void main(String[]args) throws Exception {
- Set<Student> stus = StudentInfoTool.getStudents();
- StudentInfoTool.write2File(stus);
- }
- }
- public class Student implements Comparable<Student>
- {
- private String name ;
- private int cn;
- private int ma;
- private int 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;
- this.sum = cn+ma+en;
- }
- public String toString() {
- return "Student["+name+","+cn+","+ma+","+en+"]";
- }
- public int hashCode() {
- return name.hashCode()+sum*78;
- }
- public int compareTo(Stident 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 this.name;
- }
- public int getSum() {
- return this.sum;
- }
- 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;
- }
- }
- class StudentInfoTool {
- public static Set<Student> getStudents() throws Exception {
- BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- Set<Student> stus = new Set<Student>();
- 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 write2File(Set<Student> stus) throws Exception {
- BufferedWriter bufw = new BufferedWriter(new FileWriter("stuinfo.txt"));
- for(Student stu : stus) {
- bufw.write(stu.toString()+"\t");
- bufw.write(stu.getSum());
- bufw.newLine();
- bufw.flush();
- }
- bufw.close();
- }
- }
复制代码 看完毕老师的IO,最后的练习题自己写了有异常,哪里出错了呢??
|
|