在 Java 中,为什么 nextInt() 不从该文本文件中检索每个数字?

In Java, why isn't nextInt() retrieving every number from this text file?

  public GameofLife(int gen)
  {
   generations = gen; 
   life = new boolean[20][20];
   try {
      Scanner pablo = new Scanner(new File("life100.txt"));
      pablo.nextInt(); //eliminate 100 (number of files in the list)
      while (pablo.hasNextInt())
          {
            life[pablo.nextInt()][pablo.nextInt()] = true;
          }
        } catch(Exception e){}
     out.print(Arrays.deepToString(life));
    }

我正在尝试从文本文件中读取数组的 100 对 int 坐标,但出于某种原因,此设置无法获取所有数字;在读取第 3 行后停止。 文本文件在设置中

100
1    3
1    7
1    8
1   11
1   12
1   17
2    1
2    5
2    8
3    7
3   13
3   16
3   20
4    1
4    5
4   15
4   17

一直到 19 18。然而,当我使用 out.print(Arrays.deepToString(life)); 打印它时,第三行之后的每个位置都是错误的,而我正在设置它以便每一对坐标文本文件上的开始在矩阵中为真。

这是我的 nextInt() 扫描功能的问题吗?或者是其他东西?修复它的最佳方法是什么? 我需要帮助。欢迎任何建议、评论或想法。谢谢

如果那是实际的文件内容,当它读入 3 20 时看起来您超出了数组的范围 life 中没有分配 [3][20],它会只出去[3][19].

这被你的 try/catch 块遮住了,它捕捉并掉落了 ArrayIndexOutOfBoundsException。正如评论所暗示的那样,打印堆栈跟踪是一种比什么都不做更好的默认捕获行为,后者会很快显示此错误。

试着把 e.printStackTrace(); 放在 catch 块中看看我在说什么。

因为 Java 数组是从 0 开始索引的,如果你的文件包含从 1 到 20 的行+列位置,你需要在将它添加到数组之前从文件中的值中减去 1,例如

life[pablo.nextInt() - 1][pablo.nextInt() - 1] = true;