java Android:如果方法中的语句不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5200499/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:55:02  来源:igfitidea点击:

Android: If statement in method not working

javaandroidif-statement

提问by Biggsy

I'm trying to limit variables to be above zero using an if statement and the following code just runs as if the if statement doesn't exist:

我正在尝试使用 if 语句将变量限制在零以上,并且以下代码就像 if 语句不存在一样运行:

private void startGame(int h1, int h2, int w1, int w2) {
        this.h1 = h1;
        this.w1 = w1;
        this.h2 = h2;
        this.w2 = w2;
        Intent intent = new Intent(this, Game.class);
        if((h1 > 0) || (w1 > 0) || (h2 > 0) || (w2 > 0)){
            startActivity(intent);
            }
        else {
            finish();
        }

}

回答by Jonathon Faust

One of your variables is greater than 0.

您的变量之一大于 0。

Read your if statement as "if h1 is greater than zero OR w1 is greater than zero OR ..." or more simply "if any of h1, w1, h2, w2 are greater than zero".

将您的 if 语句读为“如果 h1 大于零或 w1 大于零或...”或更简单的“如果 h1、w1、h2、w2 中的任何一个大于零”。

I think what you want is AND. You want it to read "if h1 is greater than zero AND w1 is greater than zero..."

我认为你想要的是AND。您希望它显示为“如果 h1 大于零且 w1 大于零...”

The operator for "and" is &&, not ||.

“and”的运算符是&&, not ||

if(h1 > 0 && w1 > 0 && h2 > 0 && w2 > 0){

Also, @Mahesh's comment is correct -- if you have an logic statement not behaving how you think it should, print out the variables used in that statement and "run" the logic of the statement in your head with those variables. It will become clear very quickly what's wrong.

此外,@Mahesh 的评论是正确的——如果您有一个逻辑语句不符合您的预期,请打印出该语句中使用的变量,并使用这些变量在您的头脑中“运行”语句的逻辑。很快就会明白出了什么问题。

回答by pjama

I think you meant to use a logical AND (&&) instead of OR (||)

我认为您打算使用逻辑 AND (&&) 而不是 OR (||)

What you posted will pass the check when ANY ONE dimension is above zero.

当任何一个维度大于零时,您发布的内容将通过检查。

private void startGame(int h1, int h2, int w1, int w2) {
    this.h1 = h1;
    this.w1 = w1;
    this.h2 = h2;
    this.w2 = w2;
    Intent intent = new Intent(this, Game.class);
    if((h1 > 0) && (w1 > 0) && (h2 > 0) && (w2 > 0)){
        startActivity(intent);
        }
    else {
        finish();
    }

}

}

This will ensure that all dimensions are greater than zero.

这将确保所有维度都大于零。