I have an if statement like this
int val = 1;
if (val == 0 || val == 1 || val == 2 || ...);
Is there a way to do it in a more simplified? For example:
int val = 1;
if (val == (0 || 1 || 2 || ...));
I decided to solve this by creating a function like this:
public boolean ifor(int val, int o1, int o2, int o3) {
return (val == o1 || val == o2 || val == o3);
}
But this is not enough, because if I wanted to add another parameter in ifor
, for example o4
, I could not do (should I create another function with the new parameter), or if I wanted to reduce the parameters in o1
and o2
. I honestly do not know if I explained, if you ask and I'll try to explain.
答案 0 :(得分:7)
You can generalize the function by using varargs instead:
public boolean ifor(int val, int... comparisons){
for(int o : comparisons){
if(val == o) return true;
}
return false;
}
Then you could call it like any other function, with however many comparisons you want.
答案 1 :(得分:2)
Arrays.asList(options).contains(value) // check if int value in int[] array called options
答案 2 :(得分:0)
You can have a enum or Arraylist with valid values and then use the appropriate functions to check for the value.
One such example using Array List
List list = Arrays.asList(1,2,3,4); ... if (list.contains(3)) { / ... }