1

我无法在 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';
            }
        }
    }
}
4

1 回答 1

5

这是问题rowLoop <= theGrid.lengthcolLoop <= theGrid[0].length。它应该是:

rowLoop < theGrid.length

colLoop < theGrid[0].length

错误的原因是因为您的索引上升到数组的长度。因此,如果长度为 10,则向上索引 10。这不是数组的有效索引。数组具有从0到的有效索引length - 1

于 2011-03-14T19:38:54.640 回答