简体   繁体   English

Java从文件中读取分数

[英]Java read score from file

If I have a text file with the following appearance: 如果我的文本文件具有以下外观:
john1337 score: 80 john1337得分:80
may10 score: 23 may10得分:23
dfawfawf score: 40 dfawfawf得分:40
heyhey score: 100 嘿嘿得分:100
flow32 score: 25 flow32得分:25

How do I read only the top 3 scores in order and display them? 如何仅按顺序阅读前3个得分并显示它们?
So it would be: 因此它将是:
heyhey score: 100 嘿嘿得分:100
john1337 score: 80 john1337得分:80
dfawfawf score: 40 dfawfawf得分:40

Im trying to avoid sorting the integers by the names ie 'john1337' and instead displaying the actual score-line in order, how do I do this? 我试图避免按名称(即“ john1337”)对整数排序,而是按顺序显示实际的分数线,我该怎么做?

There is a stream solution just for educational purposes, but you probably should try to implement it classical way. 有一个仅用于教育目的的流解决方案,但是您可能应该尝试以经典方式实现它。

Comparator<String> comparator = Comparator.comparing(o -> Integer.valueOf(o.split(":")[1].trim()));
Comparator<String> reversed = comparator.reversed();

Files.lines(Paths.get(PATH_TO_FILE))
        .sorted(reversed)
        .limit(3)
        .forEach(System.out::println);

Here the Comparator is used to sort all lines by score. 在这里, Comparator器用于按分数对所有行进行排序。 Then using limit the stream is truncated to be no longer than 3. 然后使用limit将流截断为不超过3。

You can't access the 3 top scores without knowing, where they are located in the file. 您无法访问3个最高得分而不知道它们在文件中的位置。 So you need to know where the top scores are located in the file. 因此,您需要知道最高分在文件中的位置。 For this, you need to read all scores from the file, parse the strings (eg. split at ":", remove the word " score" and trim the resulting strings), and evaluate the scores. 为此,您需要从文件中读取所有乐谱,解析字符串(例如,在“:”处分割,删除单词“ score”并修整生成的字符串),然后评估乐谱。 You can sort them using a hashmap or similar. 您可以使用哈希图或类似方法对它们进行排序。 So, your idea is not possible using a simple text file as datasource. 因此,使用简单的文本文件作为数据源是不可能的。 If you would use a database for example you could create a query, which returns the top 3 scores. 例如,如果您使用数据库,则可以创建一个查询,该查询返回前3个得分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM