2

I'm trying to make a battleship game, for which I need a 2D array of squares, which are the places that a person can pick. When I run my program however, I get a null pointer exception when I try to call the resetBoard() function.

Battleship class:

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);
            }
        }
    }

Driver:

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();

1 Answer 1

6

Got it- uncomment the lines in Battleship, and then move boardSize = x; above that for loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.