Groovy - Switch 語句



有時,巢狀的 if-else 語句非常常見且使用頻率很高,因此設計了一個更簡單的語句,稱為switch 語句。

switch(expression) { 
   case expression #1: 
   statement #1 
   ... 
   case expression #2: 
   statement #2 
   ... 
   case expression #N: 
   statement #N 
   ... 
   default:
   statement #Default 
   ... 
} 

此語句的一般工作原理如下:

  • 要評估的表示式放在 switch 語句中。

  • 將定義多個 case 表示式,以根據表示式的評估結果確定應執行哪一組語句。

  • 在每組 case 語句的末尾添加了break 語句。 這是為了確保一旦執行了相關的語句集,迴圈就會退出。

  • 還有一個default case 語句,如果前面的任何 case 表示式都不為真,則會執行該語句。

下圖顯示了switch-case 語句的流程。

Switch Statements

以下是 switch 語句的示例:

class Example { 
   static void main(String[] args) { 
      //initializing a local variable 
      int a = 2
		
      //Evaluating the expression value 
      switch(a) {            
         //There is case statement defined for 4 cases 
         // Each case statement section has a break condition to exit the loop 
			
         case 1: 
            println("The value of a is One"); 
            break; 
         case 2: 
            println("The value of a is Two"); 
            break; 
         case 3: 
            println("The value of a is Three"); 
            break; 
         case 4: 
            println("The value of a is Four"); 
            break; 
         default: 
            println("The value is unknown"); 
            break; 
      }
   }
}

在上面的示例中,我們首先將一個變數初始化為 2 的值。然後,我們有一個 switch 語句,它評估變數 a 的值。根據變數的值,它將執行相關的 case 語句集。上述程式碼的輸出將是:

The value of a is Two
groovy_decision_making.htm
廣告

© . All rights reserved.