我正在尝试制作战舰游戏,我需要一个2D阵列的正方形,这是一个人可以选择的地方。然而,当我运行我的程序时,当我尝试调用resetBoard()函数时,我得到一个空指针异常。
战列班:
public class Battleship
{
private Square[][] squares;
private boolean aircraftCarrierSunk;
private boolean battleshipSunk;
private boolean submarineSunk;
private boolean patrolBoatSunk;
private int boardSize;
public int turns;
public Battleship(int x)
{
squares = new Square[x][x];
// for(int i = 0; i < boardSize; i++) //not sure if I need this
// {
// for(int j = 0; j < boardSize; j++)
// {
// squares[i][j] = new Square();
// }
// }
boardSize = x;
aircraftCarrierSunk = false;
battleshipSunk = false;
submarineSunk = false;
patrolBoatSunk = false;
}
public void resetBoard()
{
for(int i = 0; i < boardSize; i++)
{
for(int j = 0; j < boardSize; j++)
{
squares[i][j].setContents(0);
}
}
}
驱动:
public static void main (String [] args)
{
Battleship game = new Battleship(5); // play on a 5 by 5 board
System.out.println("Battleship!");
System.out.println("-----------\n");
for (int gameNumber = 1; gameNumber <= 2; gameNumber++)
{
game.resetBoard();
答案 0 :(得分:6)
得到它 - 取消注释Battleship
中的行,然后将boardSize = x;
移到for循环之上。