繁体   English   中英

有没有更简单的方法来检查if语句中的多个变量

[英]Is there a more simple way to check multiple variables in an if statement

我想检查t1,t2和t3以查看它们是否在13-19的范围内。如果这三个中至少有一个然后我想返回true,如果它们都不是我想返回false。 这段代码有效但我想知道是否有一种更简洁的方式来编写它,有点像:

if (t1 || t2 || t3 >13 && <19) return true else return false?

这是我目前的代码。

public class NumberChecker {

    public static boolean hasNumber(int t1, int t2, int t3) {

        if (  (t1 >=13 && t1 <=19)   ||   (t2 >=13 && t2 <=19)   ||   (t3 >=13 
        && t3 <=19)  ) {
            return true;
        } else return false;
    }

}

干杯

每当你发现自己写作if (x) return true; else return false; if (x) return true; else return false; ,意识到你可以用更短和等效的return x;替换它return x; 起初看起来可能很奇怪,但布尔条件可以直接返回。 您不需要检查它们是否为真,然后返回true。

public static boolean hasNumber(int t1, int t2, int t3) {
    return (t1 >=13 && t1 <=19) || (t2 >=13 && t2 <=19) || (t3 >=13 && t3 <=19);
}

然后,您可以选择将公共范围检查逻辑提取到辅助方法中。 它使代码更长,但冗余更少。 如果你更喜欢这个版本,由你决定; 这是一个美学决定,真的。

public static boolean hasNumber(int t1, int t2, int t3) {
    return isInRange(t1) || isInRange(t2) || isInRange(t3);
}

private static boolean isInRange(int t) {
    return t >= 13 && t <= 19;
}

您可以使用和匿名lambda函数在一行中进行匹配:

return IntStream.of(t1, t2, t3).anyMatch(t -> t >= 13 && t <= 19);

或者您可以使用varargs从参数自动构建数组:

public static boolean hasNumber(int... ts) {
    for (int t: ts) {
        if (t >= 13 && t <= 19) {
            return true;
        }
    }

    return false;
}

(答案由@shmosel提供

暂无
暂无

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

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