Java - 使用Comparator对从文件中扫描的数据进行排序

时间:2015-10-07 22:50:57

标签: java

所以我正在编写代码,它将根据类和几个Comparators实现的Comaparable接口以各种方式对列表进行排序。所以我有一个Student类和一个Runner(用于运行程序)。我的问题是我从文件导入数据,将其添加到arrayList,使用比较器对其进行排序,然后将其打印出来。当我这样做时,我无法得到我应该得到的输出。当我在导入数据后打印出数据时,它看起来像:

Deirdre      70   62
Florence     37   90
Chris        60   68
Aaron        53   80
Elmer        91   40
Betty        79   50        

^这也是我导入的txt文件的样子。这就是输出需要看起来类似的东西。

相反,输出如下:

[Student@45ee12a7, Student@330bedb4, Student@2503dbd3, Student@4b67cf4d, Student@7ea987ac, Student@12a3a380]    

这是学生班:

public class Student implements Comparable<Student> {
private String name;
private int score1, score2;
public Student (String name, int score1, int score2){
    this.name = name;
    this.score1 = score1;
    this.score2 = score2; }
public String getName(){
    return name;  }
public int getScore1(){
    return score1;  }
public int getScore2(){
    return score2;  }
@Override
public int compareTo(Student o) {
    return this.name.compareTo(o.name);  } }

Runner类是:

public class Runner {

public static void main(String[] args) {
    File grades = new File("grades.txt");
    try{
        Scanner inScan = new Scanner(grades);
        ArrayList<Student> list = new ArrayList();
        while(inScan.hasNext()){
            Student iS =  new Student (inScan.next(), inScan.nextInt(), inScan.nextInt());
            list.add(iS);
            System.out.printf("%-10s  %3d  %3d\n", iS.getName(), iS.getScore1(), iS.getScore2()); }
        System.out.println("=======================");
        Collections.sort(list,new CompareScore1());
        System.out.println(list);
        System.out.println("=======================");
        Collections.sort(list, new CompareScore2());
        System.out.println(list);
        System.out.println("=======================");
        Collections.sort(list, new CompareSum());
        System.out.println(list);  }

    catch(FileNotFoundException fnfe){
        System.out.println("File not found: " + "grades.txt");
        System.exit(1);  } }
public static class CompareScore1 implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.getScore1() - o2.getScore1();  } }

public static class CompareScore2 implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.getScore2() - o2.getScore2(); } }

public static class CompareSum implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.getScore1() + o2.getScore2(); } }
你能告诉我我做错了什么吗?提前谢谢

0 个答案:

没有答案