目录

Nested 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的值。 根据变量的值,它将执行相关的一组语句。 上述代码的输出将是 -

i is 0, j is 1
↑回到顶部↑
WIKI教程 @2018