首页 > 解决方案 > 从文件中获取分数

问题描述

我创建了一个猜词游戏,但在显示获胜者时遇到了麻烦。

我正在创建一个包含“名称单词尝试”的 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();
    }*/

标签: javafile

解决方案


您可以使用 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());

推荐阅读