我想用以下值表示 8x8 尺寸:
[0] [1] = 1 [0] [2] = 2 [1] [1] = 1 [1] [2] = 2 [1] [3] = 3 等等
我编写了这段代码,但是每当我打印出数组时,它都会为所有奇数提供一个零,例如
[5] [3] = 0 [5] [6] = 6 [5] [5] = 0 [5] [4] = 4
int [] [] chessboard = new int [8][8];
for (int i = 0; i < chessboard.length; i++) {
chessboard [i] [0] = 0;
for (int j = 0; j < chessboard.length; j++) {
chessboard [i] [j] = j++;
}
}
最佳答案
首先,您不能使用一个数组的大小来迭代另一个数组,这是不安全的。另外,如果将列索引存储在每个框中(从 0 开始),您只需通过设置值 j
(和 j++
循环一次将值增加两倍)
int[][] chessboard = new int[8][8]; // here all values are 0 as it's an int array
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard.length; j++) {
chessboard[i][j] = j;
}
}
<小时/>
行 chessboard[i][0] = 0;
没有用,原因有两个:
- 初始值,其中 0
- 循环从 0 开始,因此它也设置了
0
关于java - 用 2D 数组表示 8x8 维度的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225089/