2012-11-12 83 views
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初學者和感謝提示

+2

在你的代碼的行做你這個例外? – 2012-11-12 14:59:32

+0

當i = 4或j = 4「時,由於i + 1或j + 1指數分別超出界限。 –

回答

7

看這個條件:

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

你想讓它什麼不做。它將永遠真實的,因爲i不能同時爲0和4

所以你最終會走進這裏的時候j是0:

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

爆炸。

0

試試這個;

替換此行;

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

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

,將確保你不會從你的數組引用與負指數或數值大於4