Reputation: 199
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
Reputation: 135762
You can't use it that way, as the ||
operator requires boolean
operands (and you are using integers).
Your alternatives are:
if
statement with each equality expression separated:if (month == 2 || month == 4 || month == 6 || month == 9 || month == 11) {
// your stuff here
}
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.)
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
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
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
Reputation: 8263
List<Integer> months = Arrays.asList(2, 4, 6, 9, 11);
if(months.contains(month)){
// do something
}
Upvotes: 1