为什么这个方法一直告诉我它缺少 return 语句?如果我删除 else,它会告诉我返回 true 无法访问。在此先感谢您的帮助 !
public static boolean Digit(String pass){
for (int i=0; i < pass.length(); i++ ){
if (!Character.isDigit(pass.charAt(i))) {
System.out.println("Must contain digits");
return false;
}
else
return true;
}
}
最佳答案
Why does this method keep telling me it's missing a return statement ?
因为在
for
之后有办法到达那个点环形。考虑 pass
的情况长度为零。更一般地说,确定语句(或代码中的点)可达性的规则在 JLS 14.22 中列出。 .一个简单的相关规则
for
循环如下:A basic
for
statement can complete normally if and only if at least one of the following is true:
- The
for
statement is reachable, there is a condition expression, and the condition expression is not a constant expression (§15.29) with value true.- There is a reachable break statement that exits the
for
statement.
在您的示例中,满足第一个要求。因此,
for
循环可以正常完成。因此在for
之后有一个返回点环形。因此一个 return
此时需要声明。请注意,可达性规则不依赖于 Java 编译器是否足够聪明来分析您的应用程序的逻辑,并且它们不会让编译器自行决定是否聪明。因此,有一些 Java 示例可以正式证明一个语句是不可到达的,但规则却说它是可到达的,并要求编译错误。
(所以在你的例子中,编译器不需要推断你的代码没有考虑零长度字符串。这是“人类水平”的推理。)
关于java - 为什么它给我一个返回丢失错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65058457/