我正在尝试使用双数组制作一个 5 x 10 的表格。第一个框应该是空白的,然后其余的编号为 2-50。
到目前为止我有这个,但它不工作。
int array[][] = new int[5][10];
for(int row=1; row<5;row++){
for(int col=1;col<10;col++)
array[row][col] = row*col;}
System.out.println(array);
row * col不能给你连续的数字2 to 50。在您的代码中,您不仅仅是离开了,first box而是完全离开了。first rowfirst column
您应该从0 to max. 对于[0][0],不要打印任何东西。
此外,对于从 打印2 to 50,只需有一个以 开头的计数变量,2打印后将其递增1。
这是修改后的代码: -
int array[][] = new int[5][10];
int count = 2;
for(int row=0; row<5;row++){
for(int col=0;col<10;col++) {
if (row == 0 && col == 0) {
continue;
}
array[row][col] = count++;
}
}
for (int[] inner: array) {
System.out.println(Arrays.toString(inner));
}
输出 : -
[0, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
笔记: -
由于您希望您first box的为空白,因此您不能Arrays.toString在此处使用。您将不得不再使用一个循环,并以简单的方式打印您的数组。当你的指数[0][0]是sysout("");
第一个框不能为空......它可以为零,这就是你想要的吗?
变化:
0索引,而不是1索引row * col不是正确的值。采用row * 10 + col + 1试试这个:
int array[][] = new int[5][10];
for(int row=0; row<5;row++){
for(int col=0;col<10;col++) {
array[row][col] = row * 10 + col + 1;
if (array[row][col] < 2) {
System.out.print(" ");
} else {
System.out.print(array[row][col]);
}
if (col < 9) System.out.print(",");
}
System.out.println();
}
输出:
,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
21,22,23,24,25,26,27,28,29,30
31,32,33,34,35,36,37,38,39,40
41,42,43,44,45,46,47,48,49,50