逐行输入到2D阵列

时间:2013-09-25 00:07:03

标签: java arrays matrix java.util.scanner

我正在做一个需要输入N×N整数矩阵的程序。输入需要使用java中的扫描程序逐行进行,并将空格作为分隔符。

输入示例:

0 0 1 0
1 0 1 1
0 1 0 1
1 0 0 0

在每个新行,它应该将它添加到矩阵,任何建议?

这就是我所拥有的:

    Scanner scanner = new Scanner(System.in);
    System.out.println("size: ");
    int size = scanner.nextInt();
    int[][] matrixAdj = new int[size][size];
    int x = 0;
    while (scanner.hasNextLine()) {
            String line = scanner.nextLine();


            String[] lineI = line.split(" ");


            for (int j = 0; j < size; j++) {
                matrixAdj[x][j] = Integer.parseInt(lineI[j]);
            }
            x++;
        }

感谢..

1 个答案:

答案 0 :(得分:0)

我假设示例输入是:

4
0 0 1 0
1 0 1 1
0 1 0 1
1 0 0 0

如果不是,那应该是因为您阅读的第一个字符是大小。

nextIntnextLine无法很好地协同工作。 nextInt不会转到下一行,因此在第一次阅读nextLine时,您最终会得到一个空字符串。

要解决此问题,请在nextLine之后直接拨打nextInt

int size = scanner.nextInt();
scanner.nextLine(); // advance to next line

或改为使用nextLine

int size = Integer.parseInt(scanner.nextLine());

或者您可以反复拨打nextInt并完全忘记nextLine

while (scanner.hasNextLine()) {
   for (int j = 0; j < size; j++) {
      matrixAdj[x][j] = scanner.nextInt();
   }
   x++;
}

虽然问题可能很难弄清楚你的输入是否有问题。

相关问题