开发者

Problem using Array[] in Do-While Loop

开发者 https://www.devze.com 2023-02-24 05:07 出处:网络
Here is a method called placeShips() that I am calling via another method (which is called by a ButtonListener).But when all are called, I get a NullPointerException on the deepest nested line - Syste

Here is a method called placeShips() that I am calling via another method (which is called by a ButtonListener). But when all are called, I get a NullPointerException on the deepest nested line - System.out.println(ships[i]);. The array has been declared and initialized above this code in the constructor. It is set to be equal to a constant integer which equals 3. I've put a simple string in that printout and it works. But whenever the array gets involved, it becomes messy. What is going wrong?

NUM_SHIPS, NC_EMPTY, NC_SHIP, and all the labels/buttons have been made as well.

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


You have a class level array variable : private Ships ships[];, yet you define in your constructor Ships[] ships = new Ships[NUM_SHIPS];. Are you ever assigning to the class level variable? you could try

/* 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());
    }
}

If that doesn't work then debug the code to find which object is actually throwing the exception


It looks like your constructor is only initializing a local variable named ships. You say you have:

-----Constructor begins here-----*
Ships[] ships = new Ships[NUM_SHIPS];
*-----Constructor ends here-----*`

But it seems like you really want

ships = new Ships[NUM_SHIPS];

0

精彩评论

暂无评论...
验证码 换一张
取 消