在没有“循环”的java中使用标签 [英] using labels in java without "loops"

查看:125
本文介绍了在没有“循环”的java中使用标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以为标签必须只用于循环,但似乎没有。给出这样的代码:

I always thought that the labels must be used only with loops but it seems not. Giving such code:

public class LabelTest {
    public static void main(String[] args) {
        label1: System.out.println("");
        label2: LabelTest t = new LabelTest();  
    }                                               
}

当标记为label1的编译行编译但代码在label2给出错误。为什么?为什么我要标记不是循环的语句?

When compiled line labeled "label1" compiles but the code at "label2" gives errors. Why's that? And why would I want to label statements which are not "loops"?

推荐答案

由于无法应用标签而出现错误变量声明,这就是如何定义语言语法(a label只能在 Statement 之前,而 LocalVariableDeclarationStatement 不是 Statement )。原因可能是它可能导致关于变量范围的混淆。这有效:

You get an error because a label cannot be applied to variable declarations, that's just how the language grammar is defined (a label can only precede a Statement, and a LocalVariableDeclarationStatement is not a Statement). The reason is probably that it could cause confusion concerning variable scope. This works:

    label1: System.out.println("");
    label2: { LabelTest t = new LabelTest(); }

这篇关于在没有“循环”的java中使用标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆