java - 继续如何工作?

标签 java for-loop while-loop break continue

我试图了解“继续”的工作原理。我理解关键字的概念,但是当我运行不同的程序时,它的工作方式不同:-/ 让我给你举几个例子:

如果我运行这个程序:

int j = 0;
int i = 0;
LABEL1: for (; i < 3; i++) {
  if (true)
    continue;
}

i 的值将是 3。到目前为止一切顺利。 让我们添加一个外循环:

int j = 0;
int i = 0;
LABEL2: for (; j < 3; j++) {
  LABEL1: for (; i < 3; i++) {
    if (true)
      continue LABEL2;
  }
}

i 的值将是... 0 !! 我不明白如果 continue 与进入外循环的标签一起使用,为什么 i 不递增。有人可以解释为什么吗? 你有一些像 break 那样棘手的事情吗?还是用 do {} while ?

非常感谢您提供的任何帮助。

最佳答案

基本的for语句结构如下:

BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

现在,来自 JLS §14.14.1.3. Abrupt Completion of for Statement :

If execution of the Statement completes abruptly because of a continue with no label, then the following two steps are performed in sequence:

  1. First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the ForUpdate part is not present, no action is taken.

  2. Second, another for iteration step is performed.

If execution of the Statement completes abruptly because of a continue with label L, then there is a choice:

  • If the for statement has label L, then the following two steps are performed in sequence:

    1. First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the ForUpdate is not present, no action is taken.

    2. Second, another for iteration step is performed.

  • If the for statement does not have label L, the for statement completes abruptly because of a continue with label L.

(强调我的)

ForUpdate,在你的例子中,是 i++。综上所述:

  • 您的第一个片段属于第一种情况,因此 i 递增。

  • 您的第二个片段属于第二种情况,因此 i 不会增加,因为 for 语句突然完成。

请注意,如果您的第二个代码段中有 continue LABEL1,则 i 会像您的第一个代码段一样递增(根据 JLS)。

作为 future 的提示,对于有关语言规则/语义的明确答案,您应该始终查阅语言规范。对于 Java,这是 JLS .

关于java - 继续如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24996852/

相关文章:

javascript - 我想使用 HTML 和 JavaScript 进行 While 循环,但是使用我当前的代码,循环不会结束

PHP - foreach 循环中的 mysqli_query

python - 为什么 while 循环停留在 raw_input? (Python)

java - 是什么导致了 "Incompatible operand types"错误?

javascript - 如何删除这个循环来单独调用div元素?

c++ - For Loop 函数参数错误

java - 使用 javaparse 解析 for 循环时出错

Java SimpleDateFormat解析的日期时间与日历日期时间不同

Java 的 toString 方法未被重写

java - 使用 java 从 servlet 获取标签的值