【问题标题】:Why does this code print 12 instead of 1? [duplicate]为什么此代码打印 12 而不是 1? [复制]
【发布时间】:2019-08-02 00:46:07
【问题描述】:
class New{
    public static void main(String args[]){
        int x=1;
        switch(x){
            default : System.out.print("default");
            case 1 : System.out.print(1);
            case 2 : System.out.print(2); 
        }
    }
}

当我使用 break 关键字时,这段代码可以正常工作。 但我不知道为什么这不能正常工作。 有人可以向我解释一下代码吗?

【问题讨论】:

  • 在你的调试器中单步调试。使用调试器并不是一项高级技能,学习使用它基本上是每个初学者在“Hello, World”之后应该做的下一件事情。

标签: java switch-statement case


【解决方案1】:

switch 语句跳转到匹配的case,并从那里继续处理,直到它看到break. 由于该代码中没有breaks,它从case 1 开始,输出1 ,然后继续 case 2 并输出 2。虽然这种情况很少见,但有时这种“进入下一个 case”是您真正想要的。但通常情况下,您希望 break 阻止它。

如果你把它移到最后,它也会说"default"

class New {
    public static void main(String args[]){
        int x=1;
        switch(x){
            case 1 : System.out.print(1);
            case 2 : System.out.print(2); 
            default : System.out.print("default");
        }
    }
}

输出

12默认

同样,如果您将x 设置为2,它将跳过case 1

class New {
    public static void main(String args[]){
        int x=2; // <===
        switch(x){
            case 1 : System.out.print(1);
            case 2 : System.out.print(2); 
            default : System.out.print("default");
        }
    }
}

输出

2默认

【讨论】:

  • 但是 x=1 对吗?那么为什么案例2会被执行呢?
  • @ThisuraThenuka - 正如我上面所说,没有break,它会继续从case 1 开始执行代码。它继续到case 2(在我后面的例子中,到default)。这就是为什么你需要break 如果你不希望这种情况发生,否则继续执行下一个案例。虽然这种情况很少见,但有时这种“落入下一个case”才是你真正想要的。
猜你喜欢
  • 2017-10-07
  • 1970-01-01
  • 2021-09-26
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 2015-02-15
相关资源
最近更新 更多