[英]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 = !false
和b
被打印出来?
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:伪代码翻译:
not b
(that is, while b
is false
) not b
(即, while b
是false
)b
(so print false
)b
(所以打印false
)b
to not b
, that is, the opposite of b
(so assign b
to true
)b
到not b
,即,相反b
(以便分配b
到true
)b
is true
, so not b
condition fails and loop terminatesb
是true
,所以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.