Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

try catch - What is the difference between while (x = false) and while (!x) in Java?

Sorry, I'm new to Java, so this question might be unclear.

I have been recently dealing with enclosing a try and catch statement in a while loop, because I wanted to make sure that getting input was enclosed from the rest of the program.

I have come across a problem where using an exclamation mark (!) in front of a variable in the while conditions (e.g. while (!done)) instead of using = false (e.g. while (done = false)) changes the way my program runs.

The former (!done) results in the try and except statements running as expected. The latter (done = false) does not, simply skipping them and moving on to the next part of the code.

I was under the impression that ! before a variable meant the same thing as var = false.

Am I mistaken?

Here's an example:

import java.util.Scanner;

public class TestOne {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int num;
        boolean inputDone = false;
        while (!inputDone) {
            try {
                System.out.print("Enter in a number here: ");
                num = input.nextInt();
                inputDone = true;
            }
            catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
        }
        System.out.println("Success!");
    }
}

Currently, compiling and running the program will go smoothly: it will prompt me for a number, typing in a letter or really long number causes it to print out the exception type and exit. Typing in a normal number causes it to print Success!

On the other hand, if I were to replace !inputDone with inputDone = false, it simply prints out Success! when I run the program.

Can anyone explain the difference to me between the ! and the = false statements in a while loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note the difference between done = false and done == false. The first one assigns done to be false and evaluates as false, the second one compares done with false and is exactly identical to !done.

So if you use:

while (done = false)
{
 // code here
}

Then done is set to false and the code within the while loop doesn't run at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...