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.