gpt4 book ai didi

java - 为什么外循环不能加条件

转载 作者:行者123 更新时间:2023-12-01 21:12:34 27 4
gpt4 key购买 nike

这是我的演示,很简单,但是我无法在外循环中添加添加i<10如果我尝试添加,它会提醒我:

This method must return a result of type String

public String testFor() {
for(int i = 0; ; i++) {
for(int j = 0; j < 10; j++) {
return "success";
}
}
}

为什么会发生这种情况?

最佳答案

JLS的相关部分是Sec 8.4.7 Method body ;相关部分是:

If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

( "complete normally" 是一个有点令人困惑的术语;它基本上意味着在不执行 returnthrowSystem.exit 语句的情况下完成)

Sec 14.21, Unreachable statements 。相关部分是:

A non-empty block that is not a switch block can complete normally iff the last statement in it can complete normally.

...

A basic for statement can complete normally iff 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.28) with value true.
  • There is a reachable break statement that exits the for statement.

The contained statement is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.

内部循环实际上与行为无关:您将看到完全相同的行为:

public String testFor() {
// Compiler error if you uncomment the condition.
for(int i = 0; /* i<10 */; i++) {
}
}

如果没有条件,则两个条件都不成立,因此循环无法正常完成;因此,它无法到达循环之后。因此,没有 return (或 throwSystem.exit )声明是必需的。

如果添加条件i<10 ,这不是编译时常量,因此循环可以正常完成。因此,您需要添加 return (或 throwSystem.exit )循环后的语句。

关于java - 为什么外循环不能加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50621783/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com