using labels in java without “loops”

前端 未结 5 560
遇见更好的自我
遇见更好的自我 2020-11-29 12:08

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         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 12:40

    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(); }
    

提交回复
热议问题