import java.io.*;
import java.util.*;public class Test {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
List c = new ArrayList(); String save;
String[] temp; try {
fr = new FileReader("C:\\test\\source.txt");  // 读文件
BufferedReader br = new BufferedReader(fr);
while ((save = br.readLine()) != null) {  // 按行读
temp = save.split(" ");                              // 用空格分开
if(temp.length == 2)
c.add(new Person(temp[0], Integer.parseInt(temp[1])));  // 分成      字符型   和     整型  
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("文件打开失败!");
System.exit(-1);
} catch (IOException e) {
System.out.println("文件读取错误!");
System.exit(-1);
} Collections.sort(c);  // 排序 try {
fw = new FileWriter("C:\\test\\result.txt");  // 写入路径
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < c.size() - 1; i++) {
String fin = c.get(i) + "\n";  // 以换行符为标准写入
bw.write(fin);
System.out.print(fin);
}
bw.close();
} catch (IOException e) {
System.out.println("文件写入错误!");
System.exit(-1);
}
}
}class Person implements Comparable {  // 1.有问题 Comparable接口
public String name;
public Integer salary; public Person(String name, Integer salary) {
this.name = name;
this.salary = salary;
} public String getName() {
return name;
} public Integer getSalary() {
return salary;
}
/*
public int compareTo(Person o) { int re = this.salary > o.getSalary() ? 1
: (this.salary < o.getSalary() ? -1 : 0);
return re;
}   */

public int compareTo(Object o) {
Person n = (Person)o;


return 0;
}
}
/*source.txt
 * 
小王 10000
小强 2345
小张 2342蜡笔小新蜡笔小新 2000
小强 1030
小周 1020Tom 3000
Jerry 1500
justin 1500
jerry 1500
Abel 1500中国 1200
张三 2000
李宗盛 2000
王二 2000
刘德华 2000*/
想问下compareTo这个应该怎么写,我写的注释的那段是什么问题(按照工资排序,姓名按照首字母排序),或者还有点其他的问题 javastringinteger

解决方案 »

  1.   

    这个应该要覆盖hashCode和equals方法吧代码实现到蛮简单的
      

  2.   

    你的 class Test 写得不错,没有什么必需修改的。
    帮你修改了一下 class Person,主要是 compareTo 函数。另加了 toString 函数。你试一试看。    /**
         * 先比较 name, 如果相同,再比较 salary;
         */
        public int compareTo(Object o) {
            int r = -1;
            if ( o instanceof Person ) {
                Person p = (Person) o;
                r = name.compareToIgnoreCase(p.name); //先比较 name
                if ( r == 0 ) {  // 如果相同
                    r = salary.compareTo(p.salary);  // 再比较 salary
                }
            }
            return r;
        }    /**
         * Override the same method of the super class
         * 这样的话,你的 result.txt 有相同的 format
         */
        public String toString() {  // 
            return name + " " + salary;
        }修改后运行结果:Abel 1500
    Jerry 1500
    jerry 1500
    justin 1500
    Tom 3000
    中国 1200
    刘德华 2000
    小周 1020
    小张 2342
    小强 1030
    小强 2345
    小王 10000
    张三 2000
    李宗盛 2000
    王二 2000
      

  3.   

    学习了,jswatcher,小弟是初学java的菜鸟,看了约瑟夫环问题,一直没看懂,也发帖了,如果你有时间的话,给我弟指点指点,谢谢!~