2017-10-19 85 views
-1

這裏後我試圖運行的代碼peice的:java.lang.ArrayIndexOutOfBoundsException:0偶檢查空

public int numIslands(char[][] grid) { 
    if(grid==null) 
     return 0; 
    else 
    { 
     int count=0; 
     gridtemp=grid; // gridtemp is a global character array 
     visited=new boolean[grid.length][grid[0].length]; //****ERROR****** 
     for(int i=0;i<grid.length;i++) 
     { 
      for(int j=0;j<grid[0].length;j++) 
      { 
       if(IslandCount(i,j)>1) 
        count++; 
      } 
     } 
     System.out.println(count); 
     return count; 
    } 
} 

此代碼拋出錯誤java.lang.ArrayIndexOutOfBoundsException:0如上所示代碼片段

+4

即使'grid'不是'null',它可以是空的,即,'grid.length == 0'。在這種情況下,'grid [0]'會拋出'ArrayIndexOutOfBoundsException'。 – Alex

+0

添加訪問的定義 – c0der

+1

問題是當'grid'爲空時,沒有'grid [0]'這樣的事情。空和空不是一回事。 (換句話說,Alex是對的,但是鍵入的速度比我快,戴夫給了你一個紅鯡魚)。 –

回答

0

長度爲0的數組不必爲空。

@Test 
public void testArrayWithLengthZero(){ 
    int[] i = new int[0]; 
    System.out.println(i==null); 
} 

輸出錯誤。

0

可能有2個問題在你的代碼

  • 貌似電網[0]爲空。檢查網格[0]。
  • 網格可能是一個長度爲0,因此,當要訪問網格[0],它拋出ArrayIndexOutOfBoundsException異常