java – while循环中标记的continue语句

以下简单示例会导致编译时错误.但目前尚不清楚为什么.
public static void main (String[] args) throws java.lang.Exception
{
    int i = 0;
    d:
    {
        System.out.println("d");
    }
    while(i < 10){

        i++;
        continue d;

    }
}

– 和 –

public static void main (String[] args) throws java.lang.Exception
{
    int i = 0;
    d:
    {
        System.out.println("d");
        while(i < 10){
            i++;
            continue d;
        }
    }
}

DEMO

但以下工作正常:

public static void main (String[] args) throws java.lang.Exception
{
    int i = 0;
    d:
    while(i < 10){
        {
            System.out.println("d");
        }
        i++;
        continue d;

    }
}

它是否允许将控制转移到while,for或do语句?它没有在JLS中说.实际上说的是:

A continue statement with label Identifier attempts to transfer
control to the enclosing labeled statement (§14.7) that has the same
Identifier as its label; that statement,which is called the continue
target,then immediately ends the current iteration and begins a new
one.

解决方法

继续意味着转到循环的开始.因此,当您继续使用标签时,标签必须处于循环状态. (这不是goto声明……)

Does it allow to tranfer control to the only while,for or do statement? It doesn’t say in the JLS.

实际上,确实如此.

这是JLS 14.6(Java 8修订版)真正说的:

“A continue statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; that statement,which is called the continue target,then immediately ends the current iteration and begins a new one.

To be precise,a continue statement with label Identifier always completes abruptly,the reason being a continue with label Identifier.

The continue target must be a while,do,or for statement,or a compile-time error occurs.

(用原文加粗!)

粗体句子说标签所附的声明(称为“继续目标”)必须是某种循环声明.

相关文章

ArrayList简介:ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增...
一、进程与线程 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程...
本文为博客园作者所写:&#160;一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/ 简单的一个类...
#############java面向对象详解#############1、面向对象基本概念2、类与对象3、类和对象的定义格式4、...
一、什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错。在java中,阻止当前方法或作用域...
Collection接口 Collection接口 Collection接口 Collection是最基本的集合接口,一个Collection代表一组...