java - 无法在 Java 中获取 Switch 案例的行为

标签 java switch-statement

我用java 6写过小代码

public class TestSwitch{

public static void main(String... args){
    int a = 1;
    System.out.println("start");
    switch(a){
        case 1:{
            System.out.println(1);
            case 3:
                System.out.println(3);
            case 4:
                System.out.println(4);
        }
        case 2:{
            System.out.println(2);
            case 5:
                System.out.println(5);
            case 7:
                System.out.println(7);
        }
            
    }
    System.out.println("end");
}
}

Output: start 1 2 end

我的编辑器正在显示“案例 3”和“案例 5”的孤立案例。它仍在运行 并显示输出。

  • Java 中有类似概念的 Nastated cases 吗?

  • 为什么它会给出以上输出?相反,我认为它将是“开始 1 结束”

    非常感谢您的回复!!

最佳答案

Switch 替换 if else 但 switch 语法 != If else 语法。

你忘了在每个 case 后面加上 break

所以条件落空了。

示例:

case 0:
          mColor.setText("#000000");
          break;

You can find that in docs

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.

public static void main(String... args){
        int a = 1;
        System.out.println("start");
        switch(a){
            case 1: 
                System.out.println(1);
                break;
            case 2:
                  System.out.println(2);
                  break;
            case 3:
                System.out.println(3);
                break;
            case 4:
                System.out.println(4);
                break;
            case 5:
                System.out.println(5);
                break;
            case 7:
                System.out.println(7);
                break;
            default:
                System.out.println("nothing");

            }

关于java - 无法在 Java 中获取 Switch 案例的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19581953/

相关文章:

java - 通过在命令行上指定多个 Maven 配置文件来堆叠属性

java - 配置 Liberty Profile 以使用 H2 数据库

java - java中如何修改当前的JPanel和JFrame

java - 在Java中为空数组设置常量值得吗?

javascript - 包含真值的 switch 语句可以写成对象字面量查找吗?

带/不带大括号的 C# Switch 语句....有什么区别?

php - switch 语句中的正则表达式

java - 如何在junit 4.8.x中执行特定的测试方法

c++ - 函数中的表达式语法错误帮助! C/C++

c - 开关盒产生错误输出