[英]Why does the Scanner not read the first line in which i call the programm?
我对编程很陌生,我必须做一个程序,在其中我得到未定义数量的整数。 前 2 个整数是 2D-Array 的大小。 我用剩余的整数填充数组。 例如 java 矩阵 2 2 0 1 0 1。所以数组大小应该是 2x2 和 0 1 0 1,但问题是扫描仪不读取整数。 如果我使用 java 矩阵并将整数放入下一行它可以工作。 问题是我必须将整数放入第一行。
Scanner sc = new Scanner(System.in);
String a = "";
while(sc.hasNextInt()){
a = a + sc.nextInt();
a = a + " ";
}
这是我用来读取整数并将它们放入一个字符串的代码的一部分。 我真的很感激一些想法,我可以如何改变它。
您可以使用带有nextInt
的扫描仪来读取用户的每一个 integer。 然后使用嵌套的 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.