Java编译行为

发布于 2024-12-19 18:45:37 字数 315 浏览 1 评论 0原文

在下面的代码中,为什么没有最后一个 return 语句就无法编译。

private boolean fileExists(final File[] files, final String name) {
   if (files == null || files.length == 0) {
        return false;
    }
   for (final File file : files) {
        return true;
    }
    return false;  // why is this neessary?
}

In the code below, why it does not compile without the last return statement.

private boolean fileExists(final File[] files, final String name) {
   if (files == null || files.length == 0) {
        return false;
    }
   for (final File file : files) {
        return true;
    }
    return false;  // why is this neessary?
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

帅气称霸 2024-12-26 18:45:37

如果 files 为空,则不会进入循环,但该函数需要返回一个 boolean。这就是为什么

If files is empty you don't enter the loop but the function need to return a boolean. That's why

鹿童谣 2024-12-26 18:45:37

因为如果 files 为空会发生什么?

对于这种情况,您需要第二个 return 语句。

Because what happens if files is empty?

You need the second return statement for that case.

甩你一脸翔 2024-12-26 18:45:37

因为files可能是空的。该方法必须在签名中定义的所有情况下返回布尔值!

because files could have been empty. The method must return a boolean value in all cases as defined in the signature!

烟酉 2024-12-26 18:45:37

如果 files 为空(毕竟编译器不知道),则不会返回任何内容。

If files is empty (the compiler doesn't know, after all) then nothing would be returned.

沉溺在你眼里的海 2024-12-26 18:45:37

因为您声明该方法返回一个布尔值

private boolean fileExists(final File[] files, final String name)

如果您不希望它返回任何内容,则将该方法声明为“void”

private void fileExists(final File[] files, final String name)

您可能确实需要“return”,因为如果两个“if”语句都为假会发生什么?

Because you declared that the method returns a boolean value

private boolean fileExists(final File[] files, final String name)

If you dont want it to return anything then declare the method as 'void'

private void fileExists(final File[] files, final String name)

You probably do need the 'return' because what happens if both 'if' statements are false?

凉城凉梦凉人心 2024-12-26 18:45:37

如果iffor中的return没有执行,我们仍然需要返回一个值。因此需要一个return语句。

查看代码,我们发现 if 中的 return 或 for 中的 return 将会被命中,但这不能被编译器推断出来。

If the return inside if and for are not executed we still need to return a value. So a return statement is required.

Looking at the code we see that either the return in the if or the for will be hit, but this cannot be inferred by the compiler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文