Groovy 嵌套Switch語(yǔ)句

2018-12-29 14:27 更新

它也可以有一個(gè)嵌套的 switch 語(yǔ)句。語(yǔ)句的一般形式如下所示 -

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

下面是嵌套switch語(yǔ)句的一個(gè)示例 -

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的變量初始化為a的值為2.然后我們有一個(gè) switch 語(yǔ)句,它計(jì)算變量 a 的值。 基于變量的值,它將執(zhí)行語(yǔ)句的相關(guān)案例集。上面的代碼的輸出將是 -

i is 0, j is 1
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)