Java 中的 while (x = false) 和 while (!x) 有什么区别? [英] What is the difference between while (x = false) and while (!x) in Java?
问题描述
抱歉,我是 Java 新手,所以这个问题可能不清楚.
Sorry, I'm new to Java, so this question might be unclear.
我最近一直在处理在 while 循环中包含 try 和 catch 语句的问题,因为我想确保获取输入是从程序的其余部分中包含的.
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.
我遇到了一个问题,即在 while 条件(例如 while (!done))中的变量前使用感叹号 (!) 而不是使用 = false(例如 while (done = false))会改变我的程序运行的方式.
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.
前者 (!done) 导致 try 和 except 语句按预期运行.后者 (done = false) 不会,只需跳过它们并转到代码的下一部分.
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.
我的印象是!在变量之前与 var = false 含义相同.
I was under the impression that ! before a variable meant the same thing as var = false.
我错了吗?
这是一个例子:
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!
另一方面,如果我用 inputDone = false 替换 !inputDone,它只会打印出 Success!当我运行程序时.
On the other hand, if I were to replace !inputDone with inputDone = false, it simply prints out Success! when I run the program.
谁能给我解释一下!和 while 循环中的 = false 语句?
Can anyone explain the difference to me between the ! and the = false statements in a while loop?
推荐答案
注意 done = false
和 done == false
之间的区别.第一个 assigns done
为 false
并评估为 false
,第二个比较 done
带有 false
并且与 !done
完全相同.
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
.
所以如果你使用:
while (done = false)
{
// code here
}
然后将 done
设置为 false
并且 while 循环中的代码根本不运行.
Then done
is set to false
and the code within the while loop doesn't run at all.
这篇关于Java 中的 while (x = false) 和 while (!x) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!