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

查看:44
本文介绍了在没有“循环"的情况下在 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"?

推荐答案

你得到一个错误,因为标签不能应用于变量声明,这就是 定义了语言语法(标签只能在StatementLocalVariableDeclarationStatement之前> 不是 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天全站免登陆