java条件我如何确保它检查所有if语句

时间:2014-12-04 20:31:02

标签: java

我无法使下面的查询方法起作用。如果isRestricted所有报告都处于状态限制状态,我需要它返回。如果是isClosed,则返回为状态关闭的所有报告。它适用于isRestricted,返回受限状态的所有报告。它也适用于返回除限制和关闭之外的所有内容,这是好的,但只返回if isClosed条件的所有内容。现在,如果我将isClosed条件移到顶部,那么它适用于isClosed,但不适用于isRestricted。我错过了什么?

 protected String getRestrictedOrClosedTerm() {
    if (isRestricted == null || "false".equals(isRestricted)) {
        return "-status:restricted  -status:closed ";
    }
    if (isRestricted.isEmpty()) {
        return "";
    }
    if ("true".equals(isRestricted)) {
       return "+status:restricted ";
    }
    if (isClosed == null || "false".equals(isClosed)) {
        return "-status:closed ";
    }
    if (isClosed.isEmpty()) {
        return "";
    }
    if ("true".equals(isClosed)) {
        return "+status:closed ";
    }

    return "";
} 

就像它停在了:

 if ("true".equals(isRestricted)) {
       return "+status:restricted ";
    }

有趣的是,如果我使用它,我会得到所需的结果,但不确定原因:

  protected String getRestrictedOrClosedTerm() {
     if ("true".equals(isClosed)) {
         return "+status:closed ";
     }
     if ("true".equals(isRestricted)) {
         return "+status:restricted ";
     }
     if (isRestricted == null || "false".equals(isRestricted)) {
        return "-status:restricted  -status:closed ";
     }
    return "";
}

1 个答案:

答案 0 :(得分:2)

在方法中使用return时,它会使用返回的值退出该方法。如果您使用类似StringBuilder的内容,则可以看到所有输出:

        protected String getRestrictedOrClosedTerm() 
        {
            StringBuilder sb = new StringBuilder();
            if (isRestricted == null || "false".equals(isRestricted)) {
                sb.append("-status:restricted  -status:closed\n");
            }
            if (isRestricted.isEmpty()) {
                sb.append("empty\n");
            }
            if ("true".equals(isRestricted)) {
                sb.append("+status:restricted\n");
            }
            if (isClosed == null || "false".equals(isClosed)) {
                sb.append("-status:closed\n");
            }
            if (isClosed.isEmpty()) {
                sb.append("empty\n");
            }
            if ("true".equals(isClosed)) {
                sb.append("+status:closed\n");
            }

            return sb.toString();
        }