简体   繁体   English

do-while循环使用continue,在Java中使用和不使用标签

[英]do-while loops with continue and with and without a label in Java

Let's look at the following do-while loop. 让我们看看下面的do-while循环。 It's quite obvious and there is no question about it. 这很明显,毫无疑问。

do
{
    System.out.println("Hello world");
    break;
} while(false);

It's quite obvious and just displays the string Hello world on the console and exits. 这很明显,只需在控制台上显示字符串Hello world并退出。


Now, the following version of do-while seems to be getting stuck into an infinite loop but it doesn't. 现在,以下版本的do-while似乎陷入了无限循环,但事实并非如此。 It also displays the string Hello world on the console and exits silently. 它还在控制台上显示字符串Hello world并以静默方式退出。

do
{
    System.out.println("Hello world");
    continue;
} while(false);

Let's see yet another version of do-while with a label as follows. 让我们看看另一个带有标签的do-while版本,如下所示。

label:do
{
    System.out.println("Hello world");
    continue label;
} while(false);

It too displays the message Hello world on the console and exits. 它也会在控制台上显示消息Hello world并退出。 It's not an infinite loop as it may seem to be means that all the versions in this scenario , work somewhat in the same way. 它不是一个无限循环,因为它似乎意味着这个场景中的所有版本都相同的方式工作。 How? 怎么样?

The continue statement means "proceed to the loop control logic for the next iteration". continue语句意味着“进入下一次迭代的循环控制逻辑”。 It doesn't mean start the next loop iteration unconditionally. 它并不意味着无条件地启动下一个循环迭代。

(If anyone wants to refer to the JLS on this, the relevant section is JLS 14.16 . However, this part of the specification is a bit complicated, and depends on the specifications of other constructs; eg the various loop statements and try / catch / finally.) (如果有人想在此引用JLS,相关部分是JLS 14.16 。但是,规范的这一部分有点复杂,并且取决于其他构造的规范;例如各种循环语句和try / catch /最后。)

Just like with a for loop, the while conditional in a do-while is always checked before entering the loop body (after the first pass through, of course). 就像for循环一样, do-whilewhile条件总是在进入循环体之前检查(当然,在第一次传递之后)。 And, just like with a for loop, continue never causes the termination expression to be skipped. 而且,就像使用for循环一样, continue永远不会导致跳过终止表达式。

The continue is checking the boolean expression before actually continuing, as the manual says: 在实际继续之前,continue正在检查布尔表达式,如手册所示:

The continue statement skips the current iteration of a for, while , or do-while loop. continue语句跳过for,while或do-while循环的当前迭代。 The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. 未标记的表单跳到最内层循环体的末尾,并计算控制循环的布尔表达式。

For more details have a look at: branching semantics 有关更多详细信息,请参阅: 分支语义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM