1

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';
            }
        }
    }
}

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That was an incredibly fast answer! And it works thank you so much!
@marsh, glad to help. Don't forget to accept this answer once the system lets you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.