我再次需要您的帮助。如何在Java中对txt文件中的记录进行排序?
这是我保存分数的代码
$string ="U+FE91";
$utf8string = html_entity_decode(preg_replace("/U\+([0-9A-F]{4})/", "&#x\\1;", $string), ENT_NOQUOTES, 'UTF-8');
$query = mysqli_query($connection, "SELECT * FROM arabicwords WHERE ArWord LIKE '%".$utf8string."%' ");
这是我如何显示分数的代码
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);
}
我当前的输出是:
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);
}
我想将分数从最高到最低排序,我该如何处理?预先谢谢你!
我想要得到的输出是:
Player1 100
Player2 200
Player3 50
答案 0 :(得分:0)
根据@ 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
您可能也想更改保存例程,但没有要求,所以我跳过了它。
答案 1 :(得分:0)
我建议使用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...
}
有了该对象,您必须创建List<Highscore>
并对该对象进行排序...
List<Highscore> highscores = new ArrayList();
//add all highscores e.g. highscores.add(new Highscore(name, totalScore));
highscores.sort(Comparator.comparing(Highscore::getScore));
排序后,您可以将高分放入文件中。