📌  相关文章
📜  在Java中为方法和函数添加标签

📅  最后修改于: 2022-05-13 01:54:18.480000             🧑  作者: Mango

在Java中为方法和函数添加标签

Java中标签的概念取自汇编语言。在Java中,break 和 continue 是控制程序流程的控制语句。标签也可以视为控制语句,但有一个强制性条件,即在循环内,标签只能与 break 和 continue 关键字一起使用。

标签的使用:

break 语句有助于在某些条件发生后退出内循环,而标签用于在内循环中使用 break 语句退出外循环。

标签在标签名称之后和循环之前使用冒号 (:) 定义。

下面是使用标签和不使用标签的代码的演示语法。

不使用标签

while (condition)  
{
 if (specific condition )
 { 
       break;
    // when control will reach to this break 
        // statement,the control will come out of while loop.
  } 
 else
     {
        // code that needs to be executed
    // if condition in if block is false.
     }
}

带标签

// labelName is the name of the label
labelName:

while (condition)  
{
 if (specific condition )
     {  
       break labelName;
    // it will work same as if break is used here.
     }
 else
     {
        // code that needs to be executed 
    // if condition in if block is false.
     } 
}



下面是一些使用 main函数的程序,它们将有助于理解标签语句的工作原理以及它们可以在哪里使用。

在单个 For 循环中使用标签

Java
// Java program to demonstrate 
// the use of label in for loop
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
    label1:
        for (int i = 0; i < 5; i++) {
            if (i == 3)
                break label1;
            System.out.print(i + " ");
        }
    }
}


Java
// Java program to demonstrate the use 
// of label in nested for loop
import java.io.*;
  
class GFG {
    
    public static void main(String[] args)
    {
    outerLoop:
        for (int i = 0; i < 5; i++) {
        innerLoop:
            for (int j = 0; j < 5; j++) {
                if (i != j) {
                    System.out.println("If block values "
                                       + i);
                    break outerLoop;
                }
                else {
                    System.out.println("Else block values "
                                       + i);
                    continue innerLoop;
                }
            }
        }
    }
}


输出
0 1 2 

在嵌套 For 循环中使用标签

Java

// Java program to demonstrate the use 
// of label in nested for loop
import java.io.*;
  
class GFG {
    
    public static void main(String[] args)
    {
    outerLoop:
        for (int i = 0; i < 5; i++) {
        innerLoop:
            for (int j = 0; j < 5; j++) {
                if (i != j) {
                    System.out.println("If block values "
                                       + i);
                    break outerLoop;
                }
                else {
                    System.out.println("Else block values "
                                       + i);
                    continue innerLoop;
                }
            }
        }
    }
}
输出
Else block values 0
If block values 0