2
我正在嘗試製作一個戰艦遊戲,爲此我需要一個二維數組的正方形,這是一個人可以選擇的地方。但是,當我運行我的程序時,當我嘗試調用resetBoard()函數時,會出現空指針異常。無法初始化Java中的對象的二維數組
戰艦類:
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();
你有沒有試過取消註釋那些你不確定的行嗎?你需要他們。 – Jeff
@Jeff是的,我仍然在「square [i] [j] .setContents(0);」 line – ahota
@AJ你可以發佈'Square'類的代碼嗎?它可能是由'setContents'方法本身產生的NPE。編輯:沒關係,user1858654說得對。 – Jeff