HOWTO · Java
Java 標籤
本教程演示瞭如何在 Java 中使用標籤。
本頁內容
標籤的概念來源於組合語言,但在 Java 中,標籤主要與用於控制程式流程的 break 和 continue 語句一起使用。本教程演示如何在 Java 中使用標籤。
在 Java 的單迴圈中使用標籤
標籤與 break 和 continue 語句一起使用,以控制迴圈的流程;讓我們嘗試一個單一 for 迴圈的示例,看看標籤 break 和 continue 語句是如何工作的。
參見示例:
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 + " ");
}
}
}
我們在要使用標籤的迴圈外部建立標籤,然後將其與 break 或 continue 語句一起使用。
見輸出:
0 1 2 3 4 5 6
0 1 2 3 4 5 6 8 9
在 Java 的巢狀迴圈中使用標籤
標籤的實際使用最適合巢狀迴圈,因為我們可以將 break 或 continue 語句應用於我們希望的迴圈;否則,預設情況下,這些語句僅適用於編寫語句的迴圈。
但是有了標籤,我們可以在我們選擇的迴圈上應用 continue 和 break 語句。
參見示例:
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 中標籤的使用。我們可以在第二個迴圈的第一個迴圈上應用 break 或 continue 語句。
見輸出:
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