首页 > 解决方案 > 有没有更简单的方法来检查 if 语句中的多个变量

问题描述

我想检查 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;
    }

}

干杯

标签: java

解决方案


Whenever you find yourself writing if (x) return true; else return false;, realize that you can replace it with the shorter and equivalent return x;. It may seem weird at first, but boolean conditions can be returned directly. You don't need to check if they're true and then return true.

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

You might then choose to extract the common range check logic into a helper method. It makes the code a bit longer, but less redundant. Up to you if you like this version better; it's an aesthetic decision, really.

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;
}

推荐阅读