简体   繁体   English

Java while 循环布尔计算

[英]Java while loop boolean evaluation

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 ?但是while(!b)设置b= true吗? like !b = !false and b is printed out?!b = !falseb被打印出来?

The while (!b) condition does not set b to true . while (!b)条件不会将b设置为true

The b = !b statement does. b = !b语句确实如此。

That's why your loop executes only once.这就是为什么你的循环只执行一次。


Translation in pseudo-code:伪代码翻译:

  • while not b (that is, while b is false ) while not b (即, while bfalse
  • print b (so print false )打印b (所以打印false
  • assign b to not b , that is, the opposite of b (so assign b to true )分配bnot b ,即,相反b (以便分配btrue
  • next iteration of the loop, b is true , so not b condition fails and loop terminates循环的下一次迭代, btrue ,所以not b条件失败并且循环终止
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 b is true so in next iteration the condition will be false and you will exist from loop因为现在b为真,所以在下一次迭代中,条件将为假,您将从循环中存在

Translated:翻译:

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

! is the negation unary operator in Java a do not modify the operand.是 Java 中的否定一元运算符 a 不修改操作数。

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.
}

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

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