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