按升序读取和写入文本文件。 (Small/annoying 错误 - 即将完成)

Reading and writing a text file in ascending order. ( Small/annoying error- nearly completed)

    Collections.sort(orderedStudents, new Comparator<Student>() {
        public int compare(Student s1, Student s2) {
            return s2.getAggregate().compareTo(s1.getAggregate());
        }
    });

这是我用的方法

问题是getAggregate方法:

public Double getAggregate(){
    double d = 0;
    double aggregatescore = d/marks.size();
    return aggregatescore;
}

由于 d 设置为零,此方法将 return 始终为 0,因此 Collections.sort(...) 方法将不执行任何操作

您编写的代码写入文件、排序数据、丢弃数据。如果你想让结果出现在文件中,你必须先排序再写入。

更像这样:

   Collections.sort(orderedStudents, new Comparator<Student>() {
        public int compare(Student s1, Student s2) {
            return s2.getAggregate().compareTo(s1.getAggregate());
        }
    });

    // Now we can do writing.
    writer = new PrintWriter(new FileOutputStream(new File("RankedList.txt")));
    for (Student s: orderedStudents) {
        s.writeToPW(writer);
    }
    writer.close();

如果顺序似乎是降序而不是升序,则在比较函数中交换 s1 和 s2。