這是一個名爲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);
}
是NUM_SHIPS等於ships.length? – 2011-04-11 01:21:44
是placeShips()和ships []數組,是同一個類的成員?您是否曾嘗試在println語句中放置斷點並查看船舶數組是否已裝運對象或數組是否爲空? – brainydexter 2011-04-11 01:22:37
您有稱爲「船」的類級別的數組變量嗎?您在嘗試在PlaceShips()中使用它之前確定要分配它嗎?此外,它更好地構造for for循環爲'for(int i = 0; i
Dan
2011-04-11 01:22:43