我正在做 Oracle 认证助理 Java SE7 程序员练习考试(书本),遇到一个问题,即使有解释,我也不明白答案。 这是解释和代码:
It will print 3. The loop body is executed twice and the program will print 3.
我不明白循环体是如何执行两次的,也许我不明白b=!b
是什么意思。有人可以解释一下吗?
class TestClass {
public static void main(String args[]){
boolean b = false;
int i = 1;
do{
i + + ;
} while (b = !b);
System.out.println(i);
}
}
最佳答案
b = !b
是一个赋值,它将 b 的逆值赋给自身(有效地在 true 和 false 之间翻转)
在 java 中,赋值返回被赋值的内容(因此 a=b=1
是可能的)
因此while (b=!b)
会翻转b的值,然后检查b的值。
关于java - 了解 do-while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20588904/