Frolicks Frolicks - 1 year ago 73
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download