使用BufferedReader将文本文件中的String和int读入HashSet Java

时间:2014-10-22 10:46:05

标签: java string int bufferedreader

文本文件如下所示:

NAME1

1

NAME2

2

方法打印:

[姓名:name1衬衫编号:1]

这就是我想要打印的方式:

[姓名:name1衬衫编号:1,姓名:name2衬衫编号:2,依此类推]

它只打印第一个元素。感觉就像我尝试了一切,但我无法让它发挥作用。有人得到了可能的解决方案吗?

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);
}

1 个答案:

答案 0 :(得分:0)

This应该有用。

readLine()函数继续到输入的下一行,因此您不需要跳过行。