我在用 Java 为二维数组赋值时遇到问题。代码的最后一行 theGrid[rowLoop][colLoop] = 'x';
引发了 ArrayIndexOutOfBoundsException
错误。有人可以解释为什么会这样吗?
这是我的代码...
public class Main {
public static char[][] theGrid;
public static void main(String[] args) {
createAndFillGrid(10,10);
}
public static void createAndFillGrid(int rows, int cols) {
theGrid = new char[rows][cols];
int rowLoop = 0;
for (rowLoop = 0; rowLoop <= theGrid.length; rowLoop++) {
int colLoop = 0;
for (colLoop = 0; colLoop <= theGrid[0].length; colLoop++) {
theGrid[rowLoop][colLoop] = 'x';
}
}
}
}
最佳答案
这里是问题rowLoop <= theGrid.length
和 colLoop <= theGrid[0].length
.应该是:
rowLoop < theGrid.length
和
colLoop < theGrid[0].length
错误的原因是因为你的索引上升到数组的长度。因此,如果长度为 10,则索引为 10。这不是数组的有效索引。数组具有来自 0
的有效索引至 length - 1
.
关于java - 无法在 Java 二维数组中赋值 - ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5303530/