0

我正在做一个程序,该程序需要输入一个 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++;
        }

谢谢..

4

1 回答 1

0

我假设示例输入是:

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

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

nextInt并且nextLine不能很好地协同工作。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++;
}

尽管问题可能很难弄清楚您的输入是否有问题。

于 2013-09-25T00:29:39.377 回答