简体   繁体   中英

Android: If statement in method not working

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:

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();
        }

}

One of your variables is greater than 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".

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

The operator for "and" is && , 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.

I think you meant to use a logical AND (&&) instead of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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