![](/img/trans.png)
[英]Why do i need an additional return statement in a method when using if-else and all possible conditions are met
[英]How to return something when ALL 3 conditions MUST be met in an if statement
弱密码定义为少于八个字符的密码。 中等密码被定义为长度为 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;
}
它应该是,
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;
}
首先将每个书面陈述翻译成逻辑陈述:
弱密码定义为少于八个字符的密码。
length < 8
中等密码被定义为长度为 8 个或更多字符且具有数字或“其他”字符的密码。
length >= 8 && (digit || other)
强密码被定义为长度为 8 个或更多字符且同时包含数字和“其他”字符的密码。
length >= 8 && digit && other
然后考虑一下您要检查这些的顺序。 先查最强,再查中,再查弱:
public String test() {
if (length >= 8 && digit && other)
return strong;
if (length >= 8 && (digit || other))
return medium;
if (length < 8)
return weak;
return null;
}
请注意在给定的约束中没有涵盖一种情况:长度为 8 或更多且没有数字且没有“其他”字符的密码。 对于这种情况,返回null
。
有几个问题。
"weak pass"
等周围加上双引号。public String test(String password)
{ int length = password.length;
if (length < 8)
etc...
之后,您可以通读它。 在第一个if
语句中,您正在测试长度是否小于 8,如果是则返回"weak pass"
。 if
您已经知道长度> = 8,那么当您到达第二个时,您就不必再进行测试了。 如果您想让其他开发人员更清楚您正在测试什么,您可以这样做,但这不是必需的,并且可能会增加混乱,让您感到困惑。
所以你在那里写了表达式((length <=8) || (length <=8 && digit) || (digit <=8 && other))
。 您可以删除<
,因为它们永远不会正确。 如果它小于 8,那么您已经在第一个 if 中返回了一些东西。 所以现在你有(length==8 || (length ==8 && digit) || (digit <=8 && other))
我不确定你的意思是digit <=8
还是length <=8
。 我假设length <= 8
,所以它是(length==8 || (length == 8 && digit) || (length == 8 && other))
如果此条件length==8
的第一部分为真,则结果为真。 这就是 boolean 包含 OR 的工作原理。 所以这意味着不再需要第二个和第三个条件,因为它们只会在length != 8
时被评估,在这种情况下(length == 8 && digit)
或(length == 8 && other)
都不为真.
最后一个if
语句(length <= 8 && digit && other)
要求length <= 8
。 但是,如果您已经在第一个或第二个 if 语句中返回了一个值,那么最后一个if
中的测试将永远不会为真。 你可以把它排除在外。
总之,你所拥有的是: if (length < 8) return weak pass; if (length == 8) return medium pass return null;
if (length < 8) return weak pass; if (length == 8) return medium pass return null;
我想您可能想阅读 boolean 逻辑。 你可能会发现or
and and
并不意味着你认为他们做的事情。 在通用语言中,它们经常互换使用,但在 boolean 逻辑中,它们具有非常精确的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.