[英]Java: How to sort the txt file?
I need your help again.我再次需要你的帮助。 how do I sort the records in the txt file in Java?如何在Java中对txt文件中的记录进行排序?
Here's the code how i save the scores这是我如何保存分数的代码
try {
File highscore = new File("highscore.txt");
PrintWriter output = new PrintWriter(new FileWriter(highscore, true));
if (highscore.exists()) {
System.out.println();
System.out.println("High Score:");
}
output.println(name + " - " + totalScore);
output.close();
} catch (IOException e) {
System.out.println(e);
}
and here's the code how I display the scores这是我如何显示分数的代码
try {
FileReader fr = new FileReader("highscore.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
My current output is:我目前的输出是:
Player1 100
Player2 200
Player3 50
And i want to sort the score from highest to lowest, how do I go about that?我想把分数从高到低排序,我该怎么做? thank you in advance!先感谢您!
the output that I want to get is:我想得到的输出是:
Player2 200
Player1 100
Player3 50
As per @luk2302 and @yshavit, you'll need to change the reading loop into something else:根据@luk2302 和@yshavit,您需要将阅读循环更改为其他内容:
while ((s = br.readLine()) != null) {
// 1. Create a custom object from found lines and push them into a list
}
// 2. Sort the list
// 3. Print the list
You might want to change the saving routine too but that wasn't asked so I'm skipping it.您可能也想更改保存程序,但没有被问到,所以我跳过了它。
i would recommend to use the java sorting function, in this case I would create an object Highscore.class
which contains name and score.我建议使用 java 排序功能,在这种情况下,我将创建一个包含名称和分数的对象Highscore.class
。
public class Highscore {
private String name;
private Integer score;
public Highscore(String name, Integer score) {
this.name = name;
this.score = score;
}
// getters...
}
Having that object, you have to create List<Highscore>
and sort over that one...拥有该对象,您必须创建List<Highscore>
并对该对象进行排序...
List<Highscore> highscores = new ArrayList();
//add all highscores e.g. highscores.add(new Highscore(name, totalScore));
highscores.sort(Comparator.comparing(Highscore::getScore));
After sorting you can put the highscores into a file.排序后,您可以将高分放入一个文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.