【问题标题】:Read both String and int from text file with BufferedReader into HashSet Java使用 BufferedReader 从文本文件中读取 String 和 int 到 HashSet Java
【发布时间】:2014-10-22 10:46:05
【问题描述】:

文本文件如下所示:

名字1

1

名字2

2

方法打印:

[姓名:姓名1 球衣号码: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);
}

【问题讨论】:

  • 因为你只添加了一个名字。尝试删除您的条件 if(counter %2)。
  • players 定义在哪里?
  • 私有最终集 player = new HashSet();玩家是我的HashSet。我有它在班级的顶部。

标签: java string int bufferedreader


【解决方案1】:

This 应该可以工作。

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

【讨论】:

  • 这种工作。我添加了 int counter = 0;否则永远不会使用变量计数器。它还警告 String name = null;永远不会使用分配的值。
  • 这行得通。谢谢您的帮助!现在回到修复代码的其他部分:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2013-04-12
  • 2017-12-01
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多