Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simpler way to check multiple values against one value in an if-statement? [duplicate]

Tags:

Basically, what I want to do is check two integers against a given value, therefore, classically what you would do is something like this:

//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);

//the actual thing in question
if(a == 0 || b == 0)
{
//Then do something
}

But is there a more concise format to do this? Possibly similar to this (which returns a bad operand type):

//just to get some values to check
int a, b;
a = (int)(Math.random()*5);
b = (int)(Math.random()*5);

//the actual thing in question
if((a||b) == 0)
{
//Then do something
}
like image 270
Amndeep7 Avatar asked Jan 22 '12 16:01

Amndeep7


People also ask

How do you compare multiple values in an if statement?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.

Which statement can check for multiple values at a time?

Switch can check for multiple values at a time.


2 Answers

You can do the following in plain java

Arrays.asList(a, b, c, d).contains(x);
like image 122
user467257 Avatar answered Sep 18 '22 08:09

user467257


Unfortunately there is no such construct in Java.

It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:

public boolean oneOfEquals(int a, int b, int expected) {
    return (a == expected) || (b == expected);
}

Then you could use it like this:

if(oneOfEquals(a, b, 0)) {
    // ...
}

If you don't want to restrict yourselft to integers, you can make the above function generic:

public <T> boolean oneOfEquals(T a, T b, T expected) {
    return a.equals(expected) || b.equals(expected);
}

Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.

like image 35
buc Avatar answered Sep 18 '22 08:09

buc