Pergunta

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';
            }
        }
    }
}
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top