缺少中断后执行的案例不正确为什么?

ncgqoxb0  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(348)

此问题已在此处找到答案

为什么我们需要在案件陈述后休息((17个答案)
5年前关闭。
我在网上学习java,来到了关于交换机的课程。为了胡闹,我在一个特定的案例(将被执行)之后删除了一个中断。我原以为它会检查下一个案例,查看条件是否为false,然后在退出之前跳到默认案例。相反,它执行了错误的案例,并在默认案例之前中断。
这里出了什么问题?

  1. public class Switch {
  2. public static void main(String[] args) {
  3. char penaltyKick = 'R';
  4. switch (penaltyKick) {
  5. case 'L': System.out.println("Messi shoots to the left and scores!");
  6. break;
  7. case 'R': System.out.println("Messi shoots to the right and misses the goal!");
  8. case 'C': System.out.println("Messi shoots down the center, but the keeper blocks it!");
  9. break;
  10. default:
  11. System.out.println("Messi is in position...");
  12. }
  13. }
  14. }

编辑:忘了提了。结果是:

  1. Messi shoots to the right and misses the goal!
  2. Messi shoots down the center, but the keeper blocks it!
lymgl2op

lymgl2op1#

如果你有一个失踪的 break ,执行将持续到下一个月 case 没有再次检查情况。请看这里:
break语句是必需的,因为如果没有它们,开关块中的语句就会失效:匹配的case标签之后的所有语句都会按顺序执行,而不管后续case标签的表达式如何,直到遇到break语句为止。

相关问题