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);
}
for (int i = 0; i < ships.Length; i++){...}