简体   繁体   English

简化if语句

[英]Simplify the if statement

I have an if statement like this 我有这样的if语句

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 . 但这还不够,因为如果我想在ifor添加另一个参数,例如o4 ,我就做不到(我应该用new参数创建另一个函数),还是我想减少o1o2的参数。 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: 您可以使用varargs来概括该函数:

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. 您可以使用具有有效值的枚举或Arraylist,然后使用相应的函数来检查值。

One such example using Array List 使用Array List的一个这样的例子

List list = Arrays.asList(1,2,3,4); List list = Arrays.asList(1,2,3,4); ... if (list.contains(3)) { / ... } ... if(list.contains(3)){/ ...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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