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))而不是using = 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
。第一个指定 已完成
为 false
并评估为 false
,第二个将 done
与 false
进行比较,与<$ c完全相同$ c>!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
}
然后已完成
设置为 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屋!