简体   繁体   中英

Simplify the if statement

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.

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.

Arrays.asList(options).contains(value) // check if int value in int[] array called options

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)) { / ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM