它也可以有一个嵌套的 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的变量初始化为a的值为2.然后我们有一个 switch 语句,它计算变量 a 的值。 基于变量的值,它将执行语句的相关案例集。上面的代码的输出将是 -
- i is 0, j is 1
转载本站内容时,请务必注明来自W3xue,违者必究。