HOWTO · Java

Java 标签

本教程演示了如何在 Java 中使用标签。

本页内容

标签的概念来源于汇编语言,但在 Java 中,标签主要与用于控制程序流程的 breakcontinue 语句一起使用。本教程演示如何在 Java 中使用标签。

在 Java 的单循环中使用标签

标签与 breakcontinue 语句一起使用,以控制循环的流程;让我们尝试一个单一 for 循环的示例,看看标签 breakcontinue 语句是如何工作的。

参见示例:

package delftstack;

class Java_Label {
  public static void main(String[] args) {
  Demo_Label1:
    for (int x = 0; x < 10; x++) {
      if (x == 7) {
        break Demo_Label1;
      }
      System.out.print(x + " ");
    }
    System.out.print("\n");
  Demo_Label2:
    for (int x = 0; x < 10; x++) {
      if (x == 7) {
        continue Demo_Label2;
      }
      System.out.print(x + " ");
    }
  }
}

我们在要使用标签的循环外部创建标签,然后将其与 breakcontinue 语句一起使用。

见输出:

0 1 2 3 4 5 6
0 1 2 3 4 5 6 8 9

在 Java 的嵌套循环中使用标签

标签的实际使用最适合嵌套循环,因为我们可以将 breakcontinue 语句应用于我们希望的循环;否则,默认情况下,这些语句仅适用于编写语句的循环。

但是有了标签,我们可以在我们选择的循环上应用 continuebreak 语句。

参见示例:

package delftstack;

class Java_Label {
  public static void main(String[] args) {
  First_Loop:
    for (int x = 0; x < 5; x++) {
    Second_Loop:
      for (int y = 0; y < 5; y++) {
        if (x == 3) {
          System.out.println("The outer Loop breaks from inside of inner loop at " + x);
          break First_Loop;
        }
        if (y == 3) {
          System.out.println("The inner loop is continued at " + y);
          continue Second_Loop;
        }
      }
    }
  }
}

上面的代码显示了 Java 中标签的使用。我们可以在第二个循环的第一个循环上应用 breakcontinue 语句。

见输出:

The inner loop is continued at 3
The inner loop is continued at 3
The inner loop is continued at 3
The outer Loop breaks from inside of inner loop at 3