简体   繁体   English

奇怪的JAVA布尔值评估问题

[英]Weird JAVA Boolean Evaluation Issue

Hi I have the following code: 嗨,我有以下代码:

  boolean result = someexpression();

            if(!result)
            {
            System.out.println("False..."); 
            }
            if (result); 
            {
                System.out.println("True");
            }

It prints both (False and true) I also tried using things like 它同时打印(False和True),我也尝试使用类似

     if(result==true)

but that doesnt seem to do the trick. 但这似乎并不能解决问题。 No matter what the value of the variable it just enters the condition.?? 无论变量的值是多少,它都只是输入条件。 I am using eclipse and this only happens at a specific portion. 我正在使用eclipse,这仅发生在特定的部分。

if (result); 

Remove the ; 删除; at the end of this line. 在此行的末尾。

With the ; ; , it means "if result is true , then do nothing". ,表示“如果resulttrue ,则不执行任何操作”。 The block that contains the next statement isn't part of the if and will always be executed. 包含下一条语句的块不是if一部分,将始终执行。 It's exactly the same as this: 与此完全相同:

if (result)   // if result is true
    ;         // then do nothing

System.out.println("True");  // is always executed

You have a rogue semi-colon at the end of your if statement. 如果if语句的末尾有流氓分号。

if (result);

This makes your code evaluate to 这使您的代码评估为

if (result) {

}
{
    System.out.println("True");
}

where the second pair of {} denotes a code block which always gets executed since it's not part of the if control block anymore. 其中第二对{}表示一个代码块,由于它不再是if控制块的一部分,因此始终可以执行。 So get rid of that semi-colon (which I assume is not what you meant to put there)! 因此,请删除该分号(我认为这不是您要放入的分号)!

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

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