Example:
int value = someValue;
if (value == (valueOne OR valueTwo OR valueThree)){
//do code
}
I would like to avoid re-typing value
You might be better off using a HashSet
Set<Integer> myset = new HashSet<Integer>();
//Add values to your set
if(myset.contains(myvalue));
{
//... Do what you want.
This allows your algorithm to be flexible and not have to manually code in new checks when you want to check against a new value.
You can't do this with if
statement in Java, but with the switch
statement.
switch (value) {
case 1:
case 2:
case 3: {
//do something
}
}
This will check if the value
is equal to 1
, 2
or 3
.
You could also use the Range class from apache commons :
Range r = Range.between(1,3);
if(r.contains(value)){
}
You use ||
to do boolean OR comparison. The single bar, |
is used for bit operations. Your current syntax is incorrect.
if(value ==1 || value==2 || value ==3)
Of course, it might be better to do a range check here like so:
if(value>=1 && value<=3)
Not sure what you're trying to do though.
If the OR comparison makes more sense for you here, you should define some constants for these values, or consider an enumerated type. The literals 1, 2, and 3 have no meaning to other developers.
This would do it in one check:
int value = someValue;
if(Arrays.asList(valueOne, valueTwo, valueThree).contains(someValue)){
// do the things
}
== tests for reference equality.
.equals() tests for value equality.
//for loop to iterate through the range of values
if(setofValues.equals( value)) ; // do something