2011-04-11 48 views
0

這是一個名爲placeShips()的方法,我通過另一種方法(由ButtonListener調用)調用。但是當所有被調用的時候,我會在最深的嵌套行 - System.out.println(ships [i]);上得到一個NullPointerException。該數組已在構造函數中的此代碼之上進行聲明和初始化。它被設置爲等於一個等於3的常量整數。我在該打印輸出中放置了一個簡單的字符串,它可以工作。但是,無論何時該陣列捲入,它都變得混亂。出了什麼問題?Do-While Loop中使用Array []的問題

NUM_SHIPS,NC_EMPTY,NC_SHIP,以及所有的標籤/按鈕都已經制作好了。

private Ships ships[]; 

*-----Constructor begins here-----* 
Ships[] ships = new Ships[NUM_SHIPS]; 
*-----Constructor ends here-----* 

ships[0] = new Ships("Aircraft Carrier", 5, false); 
ships[1] = new Ships("Battleship", 4, false); 
ships[2] = new Ships("Cruiser", 3, false); 

public void placeShips() 
{ 
    statusLabel.setText("Press [Play]"); 
    int shipsPlaced = 0; 

    do 
    { 
     int randomRow = (int)(Math.random()*ROWS); 
     int randomCol = (int)(Math.random()*COLS); 

     if (gameBoard[randomRow][randomCol] == NC_EMPTY) 
     { 
      gameBoard[randomRow][randomCol] = NC_SHIP; 
      shipsPlaced = shipsPlaced + 1; 

      for (int i = 0; i < NUM_SHIPS; i++) 
      { 
       System.out.println(ships[i]); 
      } 
     } 
    }while (shipsPlaced < NUM_SHIPS); 
} 
+0

是NUM_SHIPS等於ships.length? – 2011-04-11 01:21:44

+0

是placeShips()和ships []數組,是同一個類的成員?您是否曾嘗試在println語句中放置斷點並查看船舶數組是否已裝運對象或數組是否爲空? – brainydexter 2011-04-11 01:22:37

+0

您有稱爲「船」的類級別的數組變量嗎?您在嘗試在PlaceShips()中使用它之前確定要分配它嗎?此外,它更好地構造for for循環爲'for(int i = 0; i Dan 2011-04-11 01:22:43

回答

2

你有一個類級別數組變量:private Ships ships[];,但你在你的構造函數Ships[] ships = new Ships[NUM_SHIPS];定義。你有沒有分配到類級變量?你可以嘗試

/* Class Level */ 
private Ships _ships[]; 

/* In constructor */ 
_ships = new Ships[NUM_SHIPS]; 

/* In PlaceShips() */ 
for (int i = 0; i < _ships.Length; i++) 
{ 
    if(_ships[i] != null) 
    { 
     System.out.println(_ships[i].toString()); 
    } 
} 

如果不工作,那麼調試代碼以找到對象實際上是拋出異常

+0

+1首先識別此常見錯誤。 – camickr 2011-04-11 01:47:42

+0

謝謝。這有幫助。 – Joe 2011-04-11 01:49:11

0

它看起來像你的構造函數只初始化一個本地指定船舶的變量。你說你有:

-----Constructor begins here-----* 
Ships[] ships = new Ships[NUM_SHIPS]; 
*-----Constructor ends here-----*` 

但好像你真的想

ships = new Ships[NUM_SHIPS];

+0

這也有幫助,事實證明,我並不需要開始的船舶[]。它不再吐出錯誤!感謝大家。 – Joe 2011-04-11 01:50:08