Groovy - 複雜 switch 語句



還可以有成套的 switch 語句。語句的通用形式如下:

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

下面是一個巢狀 switch 語句的示例:-

class Example { 
   static void main(String[] args) { 
      //Initializing 2 variables i and j 
      int i = 0; 
      int j = 1; 
		
      // First evaluating the value of variable i 
      switch(i) { 
         case 0: 
            // Next evaluating the value of variable j 
            switch(j) { 
               case 0: 
                  println("i is 0, j is 0"); 
                  break; 
               case 1: 
                  println("i is 0, j is 1"); 
                  break; 
               
               // The default condition for the inner switch statement 
               default: 
               println("nested default case!!"); 
            } 
         break; 
			
         // The default condition for the outer switch statement 
         default: 
            println("No matching case found!!"); 
      }
   }
}

在上面的示例中,我們首先將一個變數初始化為 a,值是 2。然後我們使用一個 switch 語句,它對變數 a 的值進行求值。它會根據變數的值執行相關的 case 語句。上述程式碼的輸出應為:-

i is 0, j is 1
groovy_decision_making.htm
廣告
© . All rights reserved.