Java switch - 在缺少 break 后执行了不正确的 case。为什么?
Java switch - incorrect case executed after missing break. Why?
我在网上学习 Java 并在 switch 上来上课。为了愚弄,我删除了特定案例(将被执行)之后的一个中断。我原以为它会检查下一个案例,看到条件为假,然后在退出前跳到默认案例。相反,它执行了错误的案例并在默认案例之前中断。
这里出了什么问题?
public class Switch {
public static void main(String[] args) {
char penaltyKick = 'R';
switch (penaltyKick) {
case 'L': System.out.println("Messi shoots to the left and scores!");
break;
case 'R': System.out.println("Messi shoots to the right and misses the goal!");
case 'C': System.out.println("Messi shoots down the center, but the keeper blocks it!");
break;
default:
System.out.println("Messi is in position...");
}
}
}
编辑:忘了说了。输出是:
Messi shoots to the right and misses the goal!
Messi shoots down the center, but the keeper blocks it!
如果缺少 break
,执行将跳转到下一个 case
,而不会再次检查条件。参见 here:
The break statements are necessary because without them, statements
in switch blocks fall through: All statements after the matching case
label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered.
我在网上学习 Java 并在 switch 上来上课。为了愚弄,我删除了特定案例(将被执行)之后的一个中断。我原以为它会检查下一个案例,看到条件为假,然后在退出前跳到默认案例。相反,它执行了错误的案例并在默认案例之前中断。
这里出了什么问题?
public class Switch {
public static void main(String[] args) {
char penaltyKick = 'R';
switch (penaltyKick) {
case 'L': System.out.println("Messi shoots to the left and scores!");
break;
case 'R': System.out.println("Messi shoots to the right and misses the goal!");
case 'C': System.out.println("Messi shoots down the center, but the keeper blocks it!");
break;
default:
System.out.println("Messi is in position...");
}
}
}
编辑:忘了说了。输出是:
Messi shoots to the right and misses the goal!
Messi shoots down the center, but the keeper blocks it!
如果缺少 break
,执行将跳转到下一个 case
,而不会再次检查条件。参见 here:
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.