Mr Awesome8
Mr Awesome8

Reputation: 281

Java `if` statement and `else if` not working as expected

I have the user enter a list of 5 ints into an int[]. I then go through those ints in the int[] with a simple for statement. I have an int variable declared called "evens." If the number in the int[] at i %2 == 0 , evens++;

Now I have the if statement:

if (evens !=2 || evens!=3) {
  System.out.print("This was called because " + evens + " is not equal to 2 or 3");
}

The problem is that this is being called no matter what the value in evens is. It can be 5 or 3 and still gets called. I've been using C# recently but this is simple Java.

Whole code:

int evens = 0;
    for(int i=0; i<chosenNumbers.length; i++) {
        if(chosenNumbers[i] %2 ==0)
            evens++;
    }

System.out.println("You chose "+evens+" even numbers and " + (chosenNumbers.length-evens) + " odd numbers.");

    if (evens !=2 || evens!=3) {
        System.out.print("This was called because " + evens + " is not equal to 2 or 3");
    } else if (evens==2 || evens==3) {
        System.out.print(evens +" equals 2 or 3");
    }

Upvotes: 1

Views: 1254

Answers (2)

Heshan
Heshan

Reputation: 172

you can use

if(!(evens ==2 || evens==3)) {
        System.out.print("This was called because " + evens + " is not equal to 2 or 3");
} else {
        System.out.print(evens +" equals 2 or 3");
}

Upvotes: 0

AntonH
AntonH

Reputation: 6437

You need to replace:

if(evens !=2 || evens!=3) {
    System.out.print("This was called because " + evens + " is not equal to 2 or 3");
}

with:

if(evens !=2 && evens!=3) {
    System.out.print("This was called because " + evens + " is not equal to 2 or 3");
}

If you use the logical OR ||, you will always enter the block, as the only way it would not enter is it evens is equal to 2 and 3 at the same time, which isn't possible.

Upvotes: 2

Related Questions