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 var 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, or 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?