简体   繁体   English

Java中while(x = false)和while(!x)之间有什么区别?

[英]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. 对不起,我是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 (eg while (!done)) instead of using = false (eg 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. 前者(!done)导致try和except语句按预期运行。 The latter (done = false) does not, simply skipping them and moving on to the next part of the code. 后者(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! 另一方面,如果我用inputDone = false替换!inputDone,它只会打印出Success! when I run the program. 当我运行程序时。

Can anyone explain the difference to me between the ! 任何人都可以解释我之间的区别! and the = false statements in a while loop? 和while循环中的= false语句?

Note the difference between done = false and done == false . 注意done = falsedone == 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 . 第一个 done指定为false并将其评估为false ,第二个将falsefalse进行比较done!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. 然后将done设置为false并且while循环中的代码根本不运行。

The statement x = false is an assignment - you are setting x to false. 语句x = false是一个赋值 - 您将x设置为false。 The statements x == false and !x are the same, however. 但是,语句x == false!x是相同的。 The statement x == false compares x to false and will be true if the value of x is false and false if the value of x is true. 语句x == false将x与x == false进行比较,如果x值为false,则为true;如果x值为true,则为false。 The statement !x will result in the negation of the value of x . 语句!x将导致x值的否定。

In your code, if you replace while (!inputDone) with while(inputDone == false) , you will get the expected behavior. 在您的代码中,如果使用while(inputDone == false)替换while (!inputDone) while(inputDone == false) ,您将获得预期的行为。

您需要使用==而不是=进行比较。

The expression: 表达方式:

x = false

means assign x the value false . 表示将x赋值为false

After this happens in your while() , it then evaluates x , which is false so 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". 意思是“只要!x为真,继续进入循环”。 since !x means "the opposite of x". 因为!x表示“与x相反”。 So as long as x is false, the loop will continue 因此只要x为假,循环就会继续

"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是最易读的代码,它说“没有完成”

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, !done reads much better than done == false - we want "not done" (better, IMO, would be "until done" instead of "while not done"). 在可读性方面, !done读取比做得好得多done == false - 我们希望“未完成”(更好的是,IMO,将“直到完成”而不是“未完成”)。 Although (perpetual) newbies often write the redundant someCondition == true . 虽然(永久)新手经常写冗余someCondition == true

It is a good idea to make variables final , although clearly not feasible in this situation. 最好将变量设为final ,尽管在这种情况下显然不可行。 However, we can remove the flag entirely by using a break statement. 但是,我们可以使用break语句完全删除该标志。 A minority opinions follows a Single Entry Single Exit (SESE) rule, whereby break is 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. 少数意见遵循单一条目单一退出(SESE)规则,其中禁止break ,这将使此示例更棘手(您需要测试以查看文本是否是有效的int ,或者在这种情况下,移动身体进入循环。

Other answers have alluded to the fact that writing x == false and x == true are bad style. 其他答案提到了写x == falsex == true是坏风格的x == true There are three reasons for this: 这有三个原因:

  • Conciseness: assuming that you are in a context where a Boolean is required, and "x" is a Boolean, it is less characters to write x than x == true , or !x than x == false . 简洁性:假设您处于需要布尔值的上下文中,并且“x”是布尔值,则写入x字符x少于x == true!x不是x == false
  • Convention: seasoned programmers in Java (or C, C++, C# and most other languages) expect to see x rather than x == true , and !x rather than x == false . 惯例:使用Java(或C,C ++,C#和大多数其他语言)的经验丰富的程序员希望看到x而不是x == true!x而不是x == false
  • Robustness: in Java the conditional and loop statements all require a Boolean valued expression in the condition. 鲁棒性:在Java中,条件语句和循环语句都需要条件中的布尔值表达式。 If y is not a Boolean, then a typo of the form if (y = foo) { will give a compilation error in Java. 如果y不是布尔值,那么形式为if (y = foo) {的拼写错误将在Java中产生编译错误。 But if y is a Boolean then if (y = foo) { does not give a compilation error. 但是如果y是布尔值,那么if (y = foo) {不会给出编译错误。 Hence, by avoiding == for Booleans you avoid setting yourself up for a whole raft of bugs resulting from typos. 因此,通过避免==对于布尔人来说,你可以避免让自己陷入由于错别字导致的大量错误。

Many have already pointed out your misuse of = vs. == . 许多人已经指出你滥用= vs. == I would like to point out that running a static code analysis tool like Findbugs would have found this for you right away. 我想指出运行像Findbugs这样的静态代码分析工具会立即为您找到这个。

See QBA: Method assigns boolean literal in boolean expression 请参阅QBA:Method在布尔表达式中指定布尔文字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM