我试图了解“继续”的工作原理。我理解关键字的概念,但是当我运行不同的程序时,它的工作方式不同:-/ 让我给你举几个例子:
如果我运行这个程序:
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:
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.
Second, another
for
iteration step is performed.If execution of the Statement completes abruptly because of a
continue
with labelL
, then there is a choice:
If the
for
statement has labelL
, then the following two steps are performed in sequence:
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.
Second, another
for
iteration step is performed.If the
for
statement does not have labelL
, thefor
statement completes abruptly because of a continue with labelL
.
(强调我的)
ForUpdate,在你的例子中,是 i++
。综上所述:
您的第一个片段属于第一种情况,因此
i
递增。您的第二个片段属于第二种情况,因此
i
不会增加,因为for
语句突然完成。
请注意,如果您的第二个代码段中有 continue LABEL1
,则 i
会像您的第一个代码段一样递增(根据 JLS)。
作为 future 的提示,对于有关语言规则/语义的明确答案,您应该始终查阅语言规范。对于 Java,这是 JLS .
关于java - 继续如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24996852/