Java 中的 while (x = false) 和 while (!x) 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1451152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between while (x = false) and while (!x) in Java?
提问by akbiggs
Sorry, I'm new to Java, so this question might be unclear.
抱歉,我是 Java 新手,所以这个问题可能不清楚。
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 循环中包含 try 和 catch 语句的问题,因为我想确保获取输入是从程序的其余部分中包含的。
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.
我遇到了一个问题,即在 while 条件(例如 while (!done))中的变量前使用感叹号 (!) 而不是使用 = false(例如 while (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.
前者 (!done) 导致 try 和 except 语句按预期运行。后者 (done = false) 不会,只是跳过它们并转到代码的下一部分。
I was under the impression that ! before a variable meant the same thing as var = false.
我的印象是!变量之前的含义与 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.
另一方面,如果我用 inputDone = false 替换 !inputDone,它只会打印出 Success!当我运行程序时。
Can anyone explain the difference to me between the ! and the = false statements in a while loop?
任何人都可以向我解释两者之间的区别!和 while 循环中的 = false 语句?
回答by Joren
Note the difference between done = falseand done == false. The first one assignsdoneto be falseand evaluates as false, the second one compares donewith falseand is exactly identical to !done.
注意之间的差异done = false和done == false。第一个受让人done为false和的计算结果为false,第二个比较done与false和是完全相同!done。
So if you use:
所以如果你使用:
while (done = false)
{
// code here
}
Then doneis set to falseand the code within the while loop doesn't run at all.
然后done设置为false,while 循环中的代码根本不运行。
回答by Thomas Owens
The statement x = falseis an assignment - you are setting x to false. The statements x == falseand !xare the same, however. The statement x == falsecompares x to false and will be true if the value of xis false and false if the value of xis true. The statement !xwill result in the negation of the value of x.
该语句x = false是一个赋值 - 您将 x 设置为 false。但是,语句x == false和!x是相同的。该语句x == false将 x 与假进行比较,如果 的值为x假,则为真,如果 的值为真,则为假x。该语句!x将导致 的值取反x。
In your code, if you replace while (!inputDone)with while(inputDone == false), you will get the expected behavior.
在您的代码中,如果您替换while (!inputDone)为while(inputDone == false),您将获得预期的行为。
回答by Jo?o Silva
You need to use ==instead of =for comparisons.
您需要使用==而不是=进行比较。
回答by Tom Hawtin - tackline
As many others have pointed out, you have typoed ==. More interesting are the issues surrounding this.
正如许多其他人指出的那样,您打错了==. 更有趣的是围绕这一点的问题。
For language designed: Encouraging side-effects in expressions is bad. Using the symbol ==to represent mathematical =is not a good choice.
对于语言设计:鼓励表达式中的副作用是不好的。使用符号==来表示数学=并不是一个好的选择。
In terms of readability, !donereads much better than done == false- we want "not done" (better, IMO, would be "until done" instead of "while not done"). Although (perpetual) newbies often write the redundant someCondition == true.
在可读性方面,阅读!done比done == false- 我们想要“未完成”(更好,IMO,将是“直到完成”而不是“虽然未完成”)要好得多。尽管(永久)新手经常编写多余的someCondition == true.
It is a good idea to make variables final, although clearly not feasible in this situation. However, we can remove the flag entirely by using a break statement. A minority opinions follows a Single Entry Single Exit (SESE) rule, whereby breakis banned, whcih would make this example more tricky (you'd need a test to see if the text was a valid int, or in this case, move the body into the loop.
制作变量是一个好主意final,尽管在这种情况下显然不可行。但是,我们可以使用 break 语句完全删除标志。少数意见遵循 Single Entry Single Exit (SESE) 规则,break该规则被禁止,这会使此示例更加棘手(您需要进行测试以查看文本是否有效int,或者在这种情况下,将正文移入循环。
回答by Mike
The expression:
表达方式:
x = false
means assign xthe value false.
装置分配x的值false。
After this happens in your while(), it then evaluates x, which is falseso it doesn't enter the loop at all.
在您的 中发生这种情况后while(),它会评估x,false因此它根本不会进入循环。
On the other hand:
另一方面:
while (!x)
means "as long as !x is true, continue entering the loop". since !xmeans "the opposite of x". So as long as xis false, the loop will continue
意思是“只要 !x 为真,就继续进入循环”。因为!x意思是“x 的反面”。所以只要x是假的,循环就会继续
回答by Dennis C
"while(done = false)" is equals to "done=false; while(done)"
"while(done = false)" 等于 "done=false; while(done)"
It should be written as "while(done == false)" or "while(false == done)".
它应该写成“while(done == false)”或“while(false == done)”。
But still , !done is the most readable code, it say "NOT DONE"
但是, !done 是最易读的代码,它说“未完成”
回答by Stephen C
Other answers have alluded to the fact that writing x == falseand x == trueare bad style. There are three reasons for this:
其他答案暗示了写作x == false和x == true风格不好的事实。造成这种情况的原因有以下三个:
- Conciseness: assuming that you are in a context where a Boolean is required, and "x" is a Boolean, it is less characters to write
xthanx == true, or!xthanx == false. - Convention: seasoned programmers in Java (or C, C++, C# and most other languages) expect to see
xrather thanx == true, and!xrather thanx == false. - Robustness: in Java the conditional and loop statements all require a Boolean valued expression in the condition. If
yis not a Boolean, then a typo of the formif (y = foo) {will give a compilation error in Java. But ifyis a Boolean thenif (y = foo) {does not give a compilation error. Hence, by avoiding==for Booleans you avoid setting yourself up for a whole raft of bugs resulting from typos.
- 简洁:假设您处于需要布尔值的上下文中,并且“x”是布尔值,则写入的字符数
x少于x == true,或!x少于x == false。 - 约定:Java(或 C、C++、C# 和大多数其他语言)经验丰富的程序员希望看到
x而不是x == true,!x而不是x == false. - 健壮性:在 Java 中,条件语句和循环语句都需要条件中的布尔值表达式。如果
y不是布尔值,那么表单的拼写错误if (y = foo) {将在 Java 中产生编译错误。但是如果y是布尔值,则if (y = foo) {不会给出编译错误。因此,通过避免==使用布尔值,您可以避免为因拼写错误而导致的大量错误设置自己。
回答by Jeff Olson
Many have already pointed out your misuse of =vs. ==. I would like to point out that running a static code analysis tool like Findbugswould have found this for you right away.
许多人已经指出你对=vs.的误用==。我想指出的是,运行像Findbugs这样的静态代码分析工具会立即为您找到这一点。
See QBA: Method assigns boolean literal in boolean expression

