Java while 循环布尔计算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22302860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:50:16  来源:igfitidea点击:

Java while loop boolean evaluation

javawhile-loopboolean-expression

提问by user3401960

I am not sure if i understand this loop

我不确定我是否理解这个循环

boolean b = false;
while(!b) {
System.out.println(b);
b = !b;
}

it returns a false, loop is executed once

它返回一个错误,循环执行一次

but does while(!b)set b= true? like !b = !falseand bis printed out?

但是while(!b)设置了b= true吗?喜欢!b = !falseb打印出来?

回答by Mena

The while (!b)condition does not set bto true.

while (!b)条件不设置btrue

The b = !bstatement does.

b = !b声明一样。

That's why your loop executes only once.

这就是为什么你的循环只执行一次。



Translation in pseudo-code:

伪代码翻译:

  • while not b(that is, while bis false)
  • print b(so print false)
  • assign bto not b, that is, the opposite of b(so assign bto true)
  • next iteration of the loop, bis true, so not bcondition fails and loop terminates
  • while not b(即 while bis false)
  • 打印b(所以打印false
  • 分配bnot b,即b(所以分配btrue)的反义词
  • 循环的下一次迭代btrue,所以not b条件失败并且循环终止

回答by Kick

while(!b) {    // As b = false but due to ! condition becomes true not b
System.out.println(b);  //false will be printed
b = !b;  // b = !false i.e. now b is true 
}

As now bis true so in next iteration the condition will be false and you will exist from loop

因为现在b为真,所以在下一次迭代中,条件将为假,您将从循环中存在

回答by PeterMmm

!is the negation unary operator in Java a do not modify the operand.

!是 Java 中的否定一元运算符 a 不修改操作数。

回答by T McKeown

Translated:

翻译:

 boolean b = false;
 while(b == false) {
 System.out.println(b);
 b = !b;  // b becomes true
}

回答by Dr. Collage

boolean b = false;
while(!b) { // The !b basically means "continue loop while b is not equal to true"
System.out.println(b);
b = !b; // this line is setting variable b to true. This is why your loop only processes once.
}