user2826974
user2826974

Reputation: 199

boolean equality operator in If statement

I'm trying to create a if statement in which X may be equal to multiple values. Basically, I want something like

if(month == (2||4||6||9||11)); 

But, I can't do that since int can't go along with "||" operator. I would like to know how to create a if statement like that.

Upvotes: 1

Views: 130

Answers (5)

acdcjunior
acdcjunior

Reputation: 135762

You can't use it that way, as the || operator requires boolean operands (and you are using integers).

Your alternatives are:

An if statement with each equality expression separated:

if (month == 2 || month == 4 || month == 6 || month == 9 || month == 11) {
    // your stuff here
}

A switch statement with fall through:

switch (month) {
    case 2:
    case 4:
    case 8:
    case 9:
    case 11:
       // your stuff here
       break;
    default:
       // do nothing
       break;
}

(But use fall through with care, some may consider it a bad practice - as it can make your code's intentions less clear.)

Using a temporary collection and the contains() method:

if (java.util.Arrays.asList(2, 4, 6, 9, 11).contains(month)){
    // your stuff here
}

The use of one or other alternative, of course, depends on personal opinion and number of operands.



As a side note on code readability, though, my suggestion would be to get the meaning of that expression and create a method for that, which would make your code easier to understand and maintain.

So, say those months are months with "full price" (or anything that makes sense to your business rules). I'd use:

if (isFullPricedMonth(month)) {
    // your stuff here
}

And, of course, the method (with any of the solutions previously posted):

public boolean isFullPricedMonth(int month) {
    return month == 2 || month == 4 || month == 6 || month == 9 || month == 11;
}

Upvotes: 4

Oswald
Oswald

Reputation: 31647

You can ask whether the car is black or white in english. You cannot do this in most of the programming languages. In programming languages, you have to ask whether the car is black or the car is white:

if(month == 2 || month == 4 /* || month == ... */ )

Upvotes: 0

cubecubed
cubecubed

Reputation: 238

You have to compare each value with month and separate them with ||

if(month == 2 ||month == 4 ||month == 6 ||month == 9 ||month == 11);

I recommend you use a switch statement.

switch (month){
    case 2:
    case 4:
    case 6:
    case 9:
    case 11:
    //do stuff here
}

Upvotes: 0

kgautron
kgautron

Reputation: 8263

List<Integer> months = Arrays.asList(2, 4, 6, 9, 11);
if(months.contains(month)){
   // do something
}

Upvotes: 1

Thomas
Thomas

Reputation: 2211

int a = 2;
if (a == 3 || a == 4) {
    //do stuff
}

Upvotes: 1

Related Questions