0

当我编译时出现错误 java.lang.ArrayIndexOutOfBoundsException: -1。我检查了 3 次代码,没有发现错误,我也没有在数组结束后写入。

Random nahoda = new Random();    int[][] minPol = new int[5][5];
int[][] cisPol = new int[5][5];
for(int i = 0;i<5;i++)
{
for(int j=0;j<5;j++)
{
minPol[i][j] = nahoda.nextInt(2);
cisPol[i][j] = 0;
}
}
for(int i = 0;i<5;i++)
{
    for(int j=0;j<5;j++)
    {
        if(minPol[i][j]!=0)
        {
        if(i != 0 || j != 0 || i != 4 || j != 4)
        {
            cisPol[i+1][j+1]++;
            cisPol[i+1][j-1]++;
            cisPol[i-1][j+1]++;
            cisPol[i-1][j-1]++;
            cisPol[i+1][j]++;
            cisPol[i-1][j]++;
            cisPol[i][j+1]++;
            cisPol[i][j-1]++;
        }
        else
        {
            if(i == 0)
            {
                if(j == 0)
                {
                    cisPol[i+1][j+1]++;
                    cisPol[i][j+1]++;
                    cisPol[i+1][j]++;
                }
                else if(j == 4)
                {
                    cisPol[i+1][j]++;
                    cisPol[i+1][j-1]++;
                    cisPol[i][j-1]++;
                }
                else
                {
                    cisPol[i+1][j+1]++;
                    cisPol[i][j+1]++;
                    cisPol[i+1][j]++;
                    cisPol[i+1][j-1]++;
                    cisPol[i][j-1]++;
                }
            }
            else if(i == 4)
            {
                if(j == 0)
                {
                    cisPol[i-1][j+1]++;
                    cisPol[i-1][j]++;
                    cisPol[i][j+1]++;
                }
                else if(j == 4)
                {
                    cisPol[i-1][j-1]++;
                    cisPol[i-1][j]++;
                    cisPol[i][j-1]++;
                }
                else
                {
                    cisPol[i][j-1]++;
                    cisPol[i][j+1]++;
                    cisPol[i-1][j+1]++;
                    cisPol[i-1][j]++;
                    cisPol[i-1][j-1]++;
                }
            }
        }            
        }
    }
}

我是 Java 初学者,感谢您的提示

4

2 回答 2

7

看看这个条件:

if(i != 0 || j != 0 || i != 4 || j != 4)

那不会做你想做的事。它总是正确的,因为i不能同时等于 0 和 4。

j因此,当为 0时,您最终会进入这里:

cisPol[i+1][j-1]++;

砰。

于 2012-11-12T15:01:21.683 回答
0

试试这个;

替换这一行;

 if(i != 0 || j != 0 || i != 4 || j != 4)

 if( i>=1 && j>=1 && j<4 && i<4)

这将确保您不会从具有负索引或大于 4 的值的数组中引用。

于 2012-11-12T15:10:15.857 回答