문제

I'm having trouble assigning a value to my 2D array in Java. The last line of the code, theGrid[rowLoop][colLoop] = 'x';, is throwing an ArrayIndexOutOfBoundsException error. Could someone please explain why this is happening?

This is my code...

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';
            }
        }
    }
}
도움이 되었습니까?

해결책

Here is the problem rowLoop <= theGrid.length and colLoop <= theGrid[0].length. It should be:

rowLoop < theGrid.length

and

colLoop < theGrid[0].length

The reason for the error is because your index is going up to the length of the array. So, if the length were 10, you go up to index 10. This is not a valid index into the array. Arrays have valid indices from 0 to length - 1.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top