Java switch 语句 - 行为混乱
Java switch statement - Confusion in behavior
对于下面的这段代码,打印出了 10 和 98
int i = 10;
switch(i){
default:
System.out.println(100);
case 10:
System.out.println(10);
case 98:
System.out.println(98);
}
我不明白为什么 case 98 的代码得到执行,而 case 与比较值 10 不匹配。对我来说,这不是很能理解。有人可以向我解释一下吗?
非常感谢。
如果你不在每个 case 的末尾放置一个 break,则所有 case 之后与 i
的值匹配的 case 也将被执行。
switch(i){
case 10:
System.out.println(10);
break;
case 98:
System.out.println(98);
break;
default:
System.out.println(100);
}
对于下面的这段代码,打印出了 10 和 98
int i = 10;
switch(i){
default:
System.out.println(100);
case 10:
System.out.println(10);
case 98:
System.out.println(98);
}
我不明白为什么 case 98 的代码得到执行,而 case 与比较值 10 不匹配。对我来说,这不是很能理解。有人可以向我解释一下吗?
非常感谢。
如果你不在每个 case 的末尾放置一个 break,则所有 case 之后与 i
的值匹配的 case 也将被执行。
switch(i){
case 10:
System.out.println(10);
break;
case 98:
System.out.println(98);
break;
default:
System.out.println(100);
}