Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 551
Biggsy Avatar asked Apr 22 '26 09:04

Biggsy


2 Answers

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.

like image 169
Jonathon Faust Avatar answered Apr 23 '26 23:04

Jonathon Faust


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.

like image 42
pjama Avatar answered Apr 23 '26 22:04

pjama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!