0
當我編譯時,我在這裏得到了錯誤java.lang.ArrayIndexOutOfBoundsException:-1。我檢查了3次代碼,沒有發現錯誤,也沒有在數組結束後寫入。Java:數組索引超出範圍的異常
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初學者和感謝提示
在你的代碼的行做你這個例外? – 2012-11-12 14:59:32
當i = 4或j = 4「時,由於i + 1或j + 1指數分別超出界限。 –