扫描仪为什么不读取我在其中调用程序的第一行?

问题描述 投票:-1回答:1

我对编程非常陌生,我必须执行一个编程,在该程序中我得到不确定数量的整数。前两个整数是2D数组的大小。我用剩余的整数填充数组。例如,java Matrix 2 2 0 1 0 1.因此,数组大小应为2x2和0 1 0 1,但问题是扫描程序无法读取整数。如果我使用Java Matrix并将整数放入下一行,它将起作用。问题是我必须将整数放入第一行。

Scanner sc = new Scanner(System.in);
String a = "";

while(sc.hasNextInt()){
 a = a + sc.nextInt();
 a = a + " ";
}

这是我的代码的一部分,我用来读取整数并将它们放入一个字符串中。我真的很感谢我如何改变它的一些想法。

java java.util.scanner
1个回答
0
投票

您可以将扫描仪与nextInt一起使用,以从用户读取每个整数。然后使用嵌套的for循环将值插入2D数组。

Scanner in = new Scanner(System.in);
System.out.print("Enter input: ");
int row = in.nextInt();
int column = in.nextInt();
int[][] matrix = new int[row][column]; //initialize matrix with row and column entered by user
for(int r = 0; r <row; r++) {   //nested for loop to insert values from user into matrix
    for(int c = 0; c < column; c++) {
        matrix[r][c] = in.nextInt();
    }
}
for(int[] array : matrix) {    //print matrix
    System.out.println(Arrays.toString(array));
}

控制台

Enter input: 2 2 0 1 0 1
[0, 1]
[0, 1]
© www.soinside.com 2019 - 2024. All rights reserved.