简体   繁体   中英

Java Boolean while loop - Evaluating a negation

I am a beginner to Java, and although I thought I understood Boolean logic fairly well, I am being tripped up with this while loop:

boolean done = false;
while(!done) {
    String answer = JOptionPane.showInputDialog(null, "message");

    if (answer == null) finish();

    try {
        sales = Double.parseDouble(answer);
        if (sales<= 0) throw new NumberFormatException();
        else done = true;
    }

I am obviously reading this incorrectly because the code works and was taken directly from a book, but the way I would evaluate it is:

done = false,

while (done = true)

[code]

else done = true

So it would seem that this would create an infinite loop (or not start the while loop at all), but it doesn't. Can someone please help explain it?

Let's give the significant lines some line numbers:

while(!done) // (1)
{
    String answer = JOptionPane.showInputDialog(null, "message");

    if (answer == null) finish();

    try
    {
        sales = Double.parseDouble(answer); // (2)
        if (sales<= 0) throw new NumberFormatException();
        else done = true; // (3)
    }

(1) is first executed, done is false, so !done is true, so the while loop starts.

(2) gets user input, let's suppose it is more than 0, it goes to (3).

(3) set done to true.

Now let's suppose the code execution has reached the end of the while loop. (1) is executed again. This time, done is true, so !done is false. If the condition in the while loop is false, the while loop stops iterating and the code directly below the while loop is executed.

So it would seem that this would create an infinite loop

This wouldn't if you enter a number larger than or equal to 0. As I just said, a number larger than 0 will cause the while loop to stop. If you keep entering negative numbers, done will keep being false and so !done keeps being true. As a result, the while loop never stops.

You have misread the loop condition as while (done = true) , which is the opposite of the actual meaning (and uses the wrong operator). You don't compare booleans to booleans; in technical terms that is a silly action. You also don't assign a value to the loop variable in the conditional expression, because that leads to trouble, and isn't what you intended.

Let's walk through it.

done starts false . You need a boolean expression in the condition, while (!done) . The boolean expression must evaluate to true for the loop body to execute. !done => !false the first time. What is the value of !false ? It's true ! So the expression evaluates to true and the loop body executes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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