为什么会这样,
public class Bar
{
public static void main(String[] args)
{
int i = 1;
switch(i)
{
case 0:
case 1:
case 2:
System.out.println("Case 2 being executed");
break;
default:
break;
}
}
}
输出这个,
Case 2 being executed
?
当输入值显式为 1
时,如何才能输入输入值为 2
的 case block ?请注意,我知道可以通过在 1 的 case block 中添加 break
语句来避免这种行为。
最佳答案
How is it even possible to enter the case block for an input value of 2 when the input value is explicitly 1?
这种行为称为“fall-through”,这对于使用 switch-case
的初学者来说是很常见的错误。实际上,case 1:
确实首先执行。但是,由于 case 1 中没有 break
语句,因此您的 switch-case
会继续执行下一个 case,直到找到 break
语句。因此,它甚至会执行 case 2:
的代码以及输出。然后它在执行case 2
后中断,因为它遇到了中断。
因此,将您的 swich-case
更改为:-
switch(i)
{
case 0: break;
case 1: break;
case 2:
System.out.println("Case 2 being executed");
break;
default:
break;
}
查看预期的行为。
关于java - 有人可以解释一下这个 switch 语句的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14566620/