Understanding do-while loop

喜你入骨 提交于 2019-12-02 05:17:16

问题


I'm doing the oracle certified associate Java SE7 Programmer practice exams (the book) and came across a question, and I don't understand the answer even with the explanation. Here's the explanation and the code:

It will print 3. The loop body is executed twice and the program will print 3.

I don't understand how the loop body is executed twice, maybe I don't understand what the b=!b means. Can someone explain please?

class TestClass {
    public static void main(String args[]){
        boolean b = false;
        int i = 1;
        do{
            i + + ;
        } while (b = !b);
        System.out.println(i);
    }
}

回答1:


b = !b is an assignment which assigns the inverse of b to itself (effectively flipping between true and false)

in java, an assignment returns what was assigned (so that a=b=1 is possible)

therefore while (b=!b) will flip the value of b, and then check the value of b.




回答2:


b=!b

Will always be true, why? Because, what you are doing is that you insert to "b" the opposite value (T->F, F->T),and if there was no problem while (b = !b); will return TRUE....
So at your case while (b = !b); will always return true




回答3:


Iteration 1

boolean b = false; 
int i = 1; 
do{ 
    i++ ; // i = 2
} while (b = !b); // b = !false = true so one more execution

Iteration 2

do{ 
    i++ ; // i = 3
} while (b = !b); // b = !true = false so loop breaks

So it will print 3. simple :)

Actually the confusion is with = sign. = is assigning operator where as == is the conditional operator. The first will assign the value whereas later will check for the condition. You can play with it and have some other result like

int a = 6;
int b = 10;
System.out.println(a = b);
System.out.println(a == b);

and you will get the idea.




回答4:


At the end of the first iteration the variable i will be 2 because of the increment operator. The expression b=!b will result to true (b = !false) and set the variable b to true as well. So the loop gets executed again.

At the end of the second iteration the variable i is now 3. The expression b=!b will result to false (b = !true), which will be also the value of the variable b. So the whole do-while-loop terminates and the println() statement shows 3.

Keep in mind: = (assign operator) is not the same as == (equality check).




回答5:


The condition

b = !b;

uses the assignment operator, which returns the value that has been assigned.

Initially, b is false, and therefore true is assigned to b, and used for the condition. The while loop therefore executes a second time. In this execution, b is true, and therefore false is assigned to b and used for the loop condition. The loop therefore exits.



来源:https://stackoverflow.com/questions/20588904/understanding-do-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!