1

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.

1

5 Answers 5

4

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

Bah, my head is always in C#. This is the best way instead of separate checks for each value.
0

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 } 

Comments

0

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 == ... */ ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.