线程“AWT-EventQueue-0”中的异常java.lang.ArrayIndexOutOfBoundsException:10

时间:2013-04-23 05:54:43

标签: java arrays indexing

我正在使用递归方法打开扫雷,打开与块“0”相邻的所有切片。

一切顺利,直到我得到标题中提到的异常。异常在if(removalList[num1][num2] == 1){return;}处触发,但确保将删除列表中的所有初始值设置为零。 (供您参考,1表示该项目已添加到removalList以供日后删除)。

我还通过if(num1 > gameWidth || num2 > gameHeight || num1 < 0 || num2 < 0){return;}. (gameHeight and width are both 10)检查它是否在界限内,但由于某种原因它认为它超出范围。

感谢您的帮助!

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

2 个答案:

答案 0 :(得分:1)

如果数组的大小为10,则数组中可能的最大可访问索引为array[size-1]。如果您尝试访问大于或等于大小的索引,那么您将获得所谓的ArrayIndexOutOfBoundsException

例如:

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.

因此,在您的情况下,

允许

removalList[9][9],但removalList[10][10]会提供 ArrayIndexOutOfBoundsException

答案 1 :(得分:1)

没有看到更多代码,特别是removalList的声明,我只能猜测。我的猜测是,removalListgameWidth * gameHeight个元素。因此,索引从0gameWidth - 1以及从0gameHeight - 1。您的检查允许最多gameWidthgameHeight的索引,这将导致您获得的异常。