简体   繁体   English

While 循环语句

[英]While Loop Statement

I am having trouble understanding some code in Java.我无法理解 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.我被卡住的部分是while(!showShip)部分。 What does this statement mean?这个声明是什么意思?

showShip is a boolean variable, which means that it can be either true or false . showShip是一个布尔变量,这意味着它可以是truefalse while(!showShip) means that the while loop should keep looping (repeating) as long as the value of showShip is false . while(!showShip)表示只要showShip值为false ,while 循环就应该一直循环(重复)。

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

Using !使用! inverts the boolean , so the loop condition is a short way of saying反转boolean ,因此循环条件是一种简短的说法

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.当然,为了退出循环,您需要将showShip设置为true ,但是您的循环体从不这样做。 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注意:写“continue while a variable is true一种简短方法是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM