这是一个名为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