user2052855
user2052855

Reputation: 23

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 10

I'm making a minesweeper using a recursive method to open all tiles adjacent to the block "0".

Everything goes well until I get the exception I mentioned in the title. The exception is fired at if(removalList[num1][num2] == 1){return;}, but made sure to set all the initial values in the removal list to zero. (For your reference, 1 means that the item has already been added to the removalList for later removal).

I also checked to see if it was in bounds by doing if(num1 > gameWidth || num2 > gameHeight || num1 < 0 || num2 < 0){return;}. (gameHeight and width are both 10), but for some reason it thinks that it's out of bounds.

Thanks for your help!

private void function(int c5, int r5)
{
    int num1 = c5;
    int num2 = r5;

    if(num1 > gameWidth || num2 > gameHeight || num1 < 0 || num2 < 0)
    {
        return;
    }
    if(removalList[num1][num2] == 1)
    {
        return;
    }
    if(blocks[num1][num2] == 0)
    {       
        System.out.println("Added (" + num1 + ", " + num2 + ") to removal list.");
        removalList[num1][num2] = 1;

        function(num1-1, num2);
        function(num1, num2-1);
        function(num1+1, num2);
        function(num1, num2+1);

    }
    else if(blocks[num1][num2] > 0 && blocks[num1][num2] < 9)
    {
        removalList[num1][num2] = 1;
        return;
    }
    else
    {
        return;
    }
}

Upvotes: 0

Views: 22114

Answers (2)

user1271598
user1271598

Reputation:

Without seeing further code, in particular the declaration of removalList, I can only guess. My guess is, that removalList has gameWidth * gameHeight elements. So the indices run from 0 to gameWidth - 1 and from 0 to gameHeight - 1. Your check allows indices of up to gameWidth and gameHeight, which would cause the exception you are getting.

Upvotes: 1

Rahul
Rahul

Reputation: 45070

If the size of an array is 10, the max possible accessible index in the array would be array[size-1]. If you try to access an index, greater than or equal to the size, then you'd get what is called an ArrayIndexOutOfBoundsException.

E.g:-

int[] test = new int[5];
test[0] = 1; // Allowed
test[1] = 2; // Allowed
test[2] = 3; // Allowed
test[3] = 4; // Allowed
test[4] = 5; // Allowed
test[5] = 6; // NOT Allowed - You'll get the ArrayIndexOutOfBoundsException here.

Hence, in your case,

removalList[9][9] is allowed, but removalList[10][10] will give the ArrayIndexOutOfBoundsException.

Upvotes: 1

Related Questions