嗨,我正在尝试根据用户输入自动填充二维数组。 用户将输入 1 个数字,该数字将设置二维数组的大小。然后我想打印出数组的数字。 例如,如果用户输入数字 4。二维数组为 4 行 x 4 列,应包含数字 1 到 16,打印结果如下。
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
但我正在努力想出正确的说法来做到这一点。 目前我的代码只是打印出一个包含 * 的二维数组。
有谁知道如何打印出这些数字,我真的被困住了。 我的代码如下:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int num1 = input.nextInt();
int num2 = num1;
int length = num1 * num2;
System.out.println("room "+num1+"x"+num2+"="+length);
int[][] grid = new int[num1][num2];
for(int row=0;row<grid.length;row++){
for(int col=0;col<grid[row].length;col++){
System.out.print("*");
}
System.out.println();
}
}
最佳答案
读取n值,
int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
arr[i][j] = inc++;
关于java - 如何用数字自动填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11243774/