首页 > 解决方案 > 当 if 语句中必须满足所有 3 个条件时如何返回某些内容

问题描述

弱密码定义为少于八个字符的密码。中等密码被定义为长度为 8 个或更多字符且具有数字或“其他”字符的密码。强密码被定义为长度为 8 个或更多字符且同时包含数字和“其他”字符的密码。

当必须满足所有 3 个条件时,我该如何退货?我的弱传是唯一正确打印的东西。

public String test() {
//length is user input String which is already converted to into int
//digit and other are booleans,
    if (length < 8)
       return weak pass;
    if ((length <=8) || (length <=8 && digit==true) || (length<=8 && other==true))
       return medium pass
    if (length <= 8 && digit==true && other==true)
       return strong pass;
    return null;
}

标签: javaif-statement

解决方案


它应该是,

public String test() {
//length is user input String which is already converted to into int
//digit and other are booleans,
    if (length < 8)
       return weak pass;
    if (length >= 8 && digit && other)
       return strong pass;
    if (length >= 8 && (digit || other))
       return medium pass
    return null;
}

缩短版,

public String test() {
    if (length < 8) {
        return "weak";
    } else {
        if (digit && other) {
           return "strong";
        }
        if (digit || other) {
           return "medium";
        } 
    }
    return null;
}

更何况,缩短

public String test() {
    return length < 8 ? "weak" : (digit && number) ? "strong" : (digit || number) ? "medium" : null;
}

推荐阅读