在一个switch中,"默认 "情况一定是最后一个吗?

问题描述 投票:9回答:3

在java中的switch语句中,"default "的情况是否必须是最后一个?例如,我可以做如下的事情。

switch(x) {
case A: ....;
default: ....;
case B: ....;
}
java switch-statement
3个回答
18
投票

不可以,但建议放在最后,使代码更易读。下图所示的代码就很好用。

public static void main(String[] args) {

    int i = 5;
    switch (i) {
    default:
        System.out.println("hi");
        break;

    case 0:
        System.out.println("0");
        break;
    case 5:
        System.out.println("5");
        break;
    }
}

O/P : 5

5
投票

不,默认语句也可以是第一条。


-1
投票

默认 语句可以放在开关语句主体内的任何位置

   switch (i) {

          // the default statement can be placed anywhere inside the switch statement body

    }
© www.soinside.com 2019 - 2024. All rights reserved.