繁体   English   中英

减少条件运算符的数量

[英]Reduce number of conditional operators

我有一个String arraylist。 可以说

private final List<String> fruits = new ArrayList<String>();

现在我必须将输入行与arraylist中的项目进行比较

while ((line = in.readLine()) != null) {
    if (!(line.equals(fruits.get(0)) || line.contains(fruits.get(1)) ||
        line.contains(fruits.get(2)) || line.contains(fruits.get(3)) ||
        line.contains(fruits.get(4)) || line.contains(fruits.get(5)) ||
        line.contains(fruits.get(6)) || line.equals(fruits.get(7)    ||  line.equals(fruits.get(8)))) {
          //                   "DO SOMETHING"
     }
}

在某些情况下,我必须完全匹配字符串,在某些情况下,只使用包含。 但是最后,我的if子句中不应有3个以上的条件。

您的要求不清楚。 相等性检查是否仅专门针对索引78或什么。 但是无论如何,这是我的建议。 您可以创建一种简单的方法来检查line包含list中的子集

public boolean isFound(List<String> f, String l){
    for(int i=0;i<f.size();i++){
        if(l.contains(f.get(i)){
            return true;
        }
    }
    return false;
}

然后您可以像这样检查它:

if(isFound(fruits, line) || fruits.contains(line)){
    //Do Something
}

由于您要在列表中的每个水果上使用equals()或contains(),并且您的水果在不断增长,因此请考虑将列表转换为地图,在其中按水果存储所需的方法。

private enum Method {
    CONTAINS,
    EQUALS;
}

@Test
public void testFruits() throws IOException {
    Map<String, Method> methodByFruit = new HashMap<>();
    methodByFruit.put("apple", Method.CONTAINS);
    methodByFruit.put("pear", Method.CONTAINS);
    methodByFruit.put("grenade apple", Method.CONTAINS);
    methodByFruit.put("banana", Method.EQUALS);
    methodByFruit.put("kiwi", Method.EQUALS);

    BufferedReader in = new BufferedReader(new StringReader("kiwi2"));

    String line;
    while ((line = in.readLine()) != null) {
        boolean success = false;
        for (Entry<String, Method> entry : methodByFruit.entrySet()) {
            String fruit = entry.getKey();
            Method method = entry.getValue();
            if (method == Method.EQUALS) {
                success = line.equals(fruit);
            } else {
                success = line.contains(fruit);
            }
            if (success) {
                break;
            }
        }
        if (!success) {
            System.out.println("DO SOMETHING");
        }
    }
}

暂无
暂无

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

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