这是一个名为placeShips()的方法,我通过另一个方法(由ButtonListener调用)调用。但是当调用all时,我在最深的嵌套行上得到一个NullPointerException - System.out.println(ships [i]);.数组已在构造函数中的此代码上方声明和初始化。它被设置为等于3的常数整数。我在该打印输出中放了一个简单的字符串,它可以工作。但是每当阵列介入时,它就会变得混乱。出了什么问题?
还制作了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 :(得分: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());
}
}
如果这不起作用,那么调试代码以找到实际抛出异常的对象
答案 1 :(得分:0)
看起来你的构造函数只是初始化一个名为ships的局部变量。你说你有:
-----Constructor begins here-----*
Ships[] ships = new Ships[NUM_SHIPS];
*-----Constructor ends here-----*`
但似乎你真的想要
ships = new Ships[NUM_SHIPS];