简体   繁体   English

使用BufferedReader从文本文件中读取String和int到HashSet Java中

[英]Read both String and int from text file with BufferedReader into HashSet Java

The text file look like this: 文本文件如下所示:

name1 名称1

1 1个

name2 名称2

2 2

The method prints: 该方法打印:

[name: name1 shirt number: 1] [名称:name1球衣号码:1]

This is how I want it to print: 这就是我要打印的方式:

[name: name1 shirt number: 1, name: name2 shirt number: 2, and so on] [名称:name1衬衫编号:1,名称:name2衬衫编号:2,依此类推]

It only prints the first element. 它仅打印第一个元素。 Feels like I tried everything but I can't get it to work. 感觉就像我尝试了一切,但无法正常工作。 Someone got a possible solution? 有人找到了可能的解决方案?

public void loadPlayerDatabase(String fileName) throws IOException {

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

        String currentLine;
        int counter = 0;
        String name = null;

        while ((currentLine = reader.readLine()) != null) {
            int number = Integer.parseInt(reader.readLine());
            if (counter % 2 == 0) {
                name = currentLine;
                counter++;

            } else {
                Player player = new Player();
                player.setName(name);
                players.add(player);
                player.setNumber(number);
                counter++;
            }
        }
        counter++;
    } catch (NumberFormatException n) {
        System.out.println("That didn't work!" + n.getMessage());
    }
    System.out.println(players);
}

This should work. 应该工作。

The readLine() function continues on to the next line in the input and hence you don't need to skip lines. readLine()函数继续输入中的下一行,因此您无需跳过行。

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

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