[英]How to fill a 2D array with user inputted values?
我目前正在用 java 編寫一個程序,用用戶輸入的值填充二維數組。 當行和列都指定為相同的值(方陣)時,該程序可以完美運行。 但是,當值不同時,它不會打印並拋出索引越界異常,我似乎無法弄清楚原因。 我在下面附上了我的代碼。
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int x; //columns
int y; //rows
System.out.println("Enter the number of rows of the matrix:");
y = console.nextInt();
System.out.println("Enter the number of columns of the matrix:");
x = console.nextInt();
int[][] matrix = new int[y][x];
fillMatrix(y, x, matrix);
}
public static void fillMatrix(int row, int col, int[][] matrix) {
Scanner console = new Scanner(System.in);
int quantity = (row * col); //number of numbers in matrix
System.out.println("Please enter " + quantity +
" integers separated by spaces:");
for (int cinput = 0; cinput < row; cinput++) { //column
for (int rinput = 0; rinput < col; rinput++) { //row
//Read the line of integers to fill positions in the array.
matrix[cinput][rinput] = console.nextInt();
}
}
System.out.println();
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
//Outputs the array in a xy grid.
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
我要做的是復制您需要放入矩陣的所有數字。 持有一個計數器,該計數器僅在您將一個值放入矩陣時才會增加。 繼續增加計數器,直到沒有更多值可以放置。 完成后,只需退出循環即可。
像這樣的東西
Scanner myScanner = new Scanner (System.in);
int x; //columns
int y; //rows
System.out.println("Enter the number of rows of the matrix:");
y = myScanner.nextInt();
System.out.println("Enter the number of columns of the matrix:");
x = myScanner.nextInt();
int [][] matrix = new int [x][y];
myScanner.nextLine();
System.out.println("Enter the numbers seperated by space:");
String input = myScanner.nextLine();
String tmp [] = input.split(" "); //holds the numbers that are inputted (String)
int numbers [] = new int[tmp.length];//array that holds the parsed numbers
for(int i = 0 ; i <numbers.length; i++)
numbers[i] = (int)(tmp[i].charAt(0) - '0'); //parsing the numbers
// Logic that matters
int counter = 0;
for(int k = 0; k < matrix.length && counter < numbers.length; k++)
{
for(int j = 0 ; counter < numbers.length && j < matrix[k].length; j++)
{
matrix[k][j] = numbers[counter];
System.out.print(matrix[k][j]+" ");
counter = counter + 1;
}
System.out.println("");
}
輸入-
Enter the number of rows of the matrix:
3
Enter the number of columns of the matrix:
1
Enter the numbers seperated by space:
1 2 3
輸出 -
1 2 3
在您的輸出代碼中,更改i
和j
的順序。
所以改變:
matrix[i][j]
到:
matrix[j][i]
您可能也應該交換 for 循環的順序,這樣行在外面,列在里面。
放在一起,看起來像:
System.out.println();
for(int j = 0; j < row; j++)
{
for(int i = 0; i < col; i++)
{
System.out.print(matrix[j][i] + " ");
}
System.out.println();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.