本帖最后由 ゞSunペ果果つ 于 2013-5-3 08:58 编辑
- <div class="blockcode"><blockquote>import java.io.*;
- import java.util.*;
- import java.lang.*;
- public class Test31
- {
-
- public static void main(String[] args) throws IOException
- {
- Set<Student> students=StudentTool.getStudent();
- StudentTool.write2file(students);
- }
- }
- class Student implements Comparable<Student>
- {
- String name;
- int ma,cn,en;
- int sum;
- public Student(String name,int ma,int cn,int en){
- this.name=name;
- this.ma=ma;
- this.cn=cn;
- this.en=en;
- this.sum=ma+cn+en;
- }
- 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){
- <font color="red">int n=new Integer(this.name).compareTo(new Integer(s.sum));</font>
- if(n==0)
- return this.name.compareTo(s.name);
- else
- return n;
- }
- public String toString(){
- return "student["+name+"-"+ma+"-"+cn+"-"+en+"]";
- }
- }
- class StudentTool
- {
- public static Set<Student> getStudent()throws IOException{
- BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- Set <Student> students=new TreeSet<Student>();
- while((line=buff.readLine())!=null){
- //BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
- if(line.equals("ober")){
- break;
- }
- String []stu=line.split(",");
- //System.out.println(stu[0],Integer.parseInt(stu[1]),Integer.parseInt(stu[2]));
- Student s=new Student(stu[0],Integer.parseInt(stu[1]),Integer.parseInt(stu[2]),Integer.parseInt(stu[3]));
- students.add(s);
- }
- buff.close();
- return students;
- }
- public static void write2file(Set<Student> set)throws IOException{
- File f=new File("a.txt");
- f.createNewFile();
- BufferedWriter buf=new BufferedWriter(new FileWriter(f));
- for(Student s:set){
- buf.write(s.toString());
- buf.write(s.getSum());
- buf.newLine();
- buf.flush();
- }
- buf.close();
-
- }
- }
复制代码 我没有写注释是希望大家运行一下就可以看到效果了,贴就贴出来呗,求助无望,最终决定重新来过...
昨天下午拿出了这份打印出来有错误的代码,我看了一眼,自己找到了错误。
public int compareTo(Student s){
int n=new Integer(this.name).compareTo(new Integer(s.sum));//就是这句的问题
if(n==0)
return this.name.compareTo(s.name);
else
return n;
}
|
|