java - 从文件中获取分数
问题描述
我创建了一个猜词游戏,但在显示获胜者时遇到了麻烦。
我正在创建一个包含“名称单词尝试”的 result.txt 文件
然后我正在阅读该文件并尝试确定尝试次数最少的人。
所以例如
Mike Keyboard 4
John Monitor 2
我想通过 2 次尝试将 John 显示为获胜者。
我试过的一些代码
String user = null;
int min = 0;
int attempts=0;
ArrayList<String> players = new ArrayList<>();
File file = new File("result.txt");
try (Scanner scan = new Scanner(new File("result.txt"))) {
while(scan.hasNext()){
players.add(scan.nextLine());
}
System.out.println(players);
}
我知道这不起作用,但我也尝试过这样的事情。
//System.out.println("------------Player List------------");
/* try {
Scanner in = new Scanner(new File("result.txt"));
while(in.hasNext()){
user = in.next();
String word = in.next();
System.out.println(user + " ");
while (in.hasNextInt())
{
attempts = in.nextInt();
}
min = Math.min(attempts,min);
System.out.println("User: "+user+" has " + attempts+ " attempts.");
attempts = 0;
}
in.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
解决方案
您可以使用 Java8 这样做,
Path path = Paths.get("src/main/resources", "data.txt");
try (Stream<String> lines = Files.lines(path)) {
String[] winner = lines.map(l -> l.split(" "))
.reduce((a1, a2) -> Integer.valueOf(a1[2]) < Integer.valueOf(a2[2]) ? a1 : a2)
.orElseThrow(IllegalArgumentException::new);
System.out.println(Arrays.toString(winner));
}
读取文件的每一行,将其拆分为一个数组,然后根据尝试次数进行缩减,保持尝试次数最少的那个。然后从结果中提取您需要的内容。
如果您有多个获胜者并想获得所有获胜者,则减少步骤将不起作用。您可能必须将它们收集到TreeMap
其中 key 是分数,value 是具有该分数的玩家的名字。然后获得第一个条目,因为这是得分最低的条目。这是代码。
TreeMap<Integer, List<String>> winners = lines.map(l -> l.split(" "))
.collect(Collectors.groupingBy(a -> Integer.valueOf(a[2]), TreeMap::new,
Collectors.mapping(a -> a[0], Collectors.toList())));
System.out.println(winners.firstEntry());
推荐阅读
- batch-file - 使用 CMD 制作我自己的 CLI(命令行界面)
- python - 缺少 1 个必需的位置参数:'dictVar' Python
- python - 在for循环之后,我只打印了一个图像文件夹的字符串路径,而不是多个图像字符串,python
- reactjs - 带有参数的嵌套导航在 react-router-dom 中不起作用
- install4j - 如何从自定义代码中调用“从 XML 文件中读取值”操作?
- sql - 在oracle sql中的给定字符串之间提取变量字符串
- java - Jstl在验证Spring中等于String
- freemarker - 如何使用 apache freemarker 比较两个列表?
- wordpress - 如何在存档页面中显示所有类别而不是帖子?
- ruby-on-rails - 如何使用 rails 中的 link_to 从其他控制器呈现表单?