Frolicks Frolicks - 5 days ago 6
Java Question

How to repeatedly instantiate an object in a do-while loop?

I'm writing a Battleship clone in Java. I have a standard Ship class, which has a constructor that takes input from the user.

The ship has a boolean field, valid, which is calculated after the ship object's constructed.

I want to keep instantiating the Ship until it's valid, but the compiler throws me a "cannot find symbol (patrolBoats)". Why? How do I get around this?

do {
Ship patrolBoat = new Ship(2, "Patrol Boat", promptInputForEnds("Patrol Boat", 2, kboard));
} while (patrolBoat.valid);

Answer

You're declaring the patrolBoat variable inside the loop, so it's not in the scope of the while statement.

Declare Ship patrolBoat before the loop:

Ship patrolBoat;
do {
  patrolBoat = ...
} while (patrolBoat.valid);
Comments