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
Java while loop boolean evaluation
提问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 = !false
and b
is printed out?
但是while(!b)
设置了b= true
吗?喜欢!b = !false
并b
打印出来?
回答by Mena
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, whileb
isfalse
) - print
b
(so printfalse
) - assign
b
tonot b
, that is, the opposite ofb
(so assignb
totrue
) - next iteration of the loop,
b
istrue
, sonot b
condition fails and loop terminates
- while
not b
(即 whileb
isfalse
) - 打印
b
(所以打印false
) - 分配
b
给not b
,即b
(所以分配b
给true
)的反义词 - 循环的下一次迭代
b
是true
,所以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.
}