在java中的switch语句中,"default "的情况是否必须是最后一个?例如,我可以做如下的事情。
switch(x) {
case A: ....;
default: ....;
case B: ....;
}
不可以,但建议放在最后,使代码更易读。下图所示的代码就很好用。
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
不,默认语句也可以是第一条。
的 默认 语句可以放在开关语句主体内的任何位置
switch (i) {
// the default statement can be placed anywhere inside the switch statement body
}