While Loop Declaration

advertisements

I am having trouble understanding some code in Java. I have researched around but I am still having trouble fully understanding it.

boolean showShip = false; //set the ship to be hidden by default

while(!showShip) //dont get this while loop
{
  val = promptForInt("\n" + "Guess again. "); 

  if(val == randomShipLocation)
  {
    System.out.println("\n" +" BOOM!");
    showShip = false;
    riverLength[val] = 1; // mark a hit
  }
  else {
    riverLength[val] = -1; // mark a miss
  }

  displayRiver(riverLength, showShip);
}

The part I am getting stuck on is the while(!showShip) part. What does this statement mean?


while(!showShip) // don't get this while loop

Using ! inverts the boolean, so the loop condition is a short way of saying

while(showShip == false) // This is the long way

Of course in order to exit the loop you need to set showShip to true, but the body of your loop never does it. Therefore, the loop is infinite. Most likely, the intention has been to do

System.out.println("\n" +" BOOM!");
showShip = true;

Note: A short way to write "continue while a variable is true is

while (showShip) // skip the == true part