gpt4 book ai didi

Java 开关 - 在缺少中断后执行不正确的情况。为什么?

转载 作者:行者123 更新时间:2023-11-29 06:55:33 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why do we need break after case statements?

(17 个回答)


6年前关闭。




我在网上学习 Java 并来到了关于 switch 的类(class)。为了鬼混,我在特定情况(将被执行)之后删除了一个中断。我原以为它会检查下一个案例,看看条件是否为假,然后在退出之前跳到默认案例。相反,它执行了错误的案例并在默认案例之前中断。

这里出了什么问题?

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 开关 - 在缺少中断后执行不正确的情况。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34977292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com