[英]Switch Statement Default Case Fall Through
Here is a small confusion so kindly pardon my ignorance. 这是一个小混乱,请原谅我的无知。 Here is a code snippet. 这是一个代码片段。
public class SwitchTest {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 1:
System.out.println("1");
break;
default:
System.out.println("helllo");
case 2:
System.out.println("Benjamin");
break;
}
}
}
Here, if value of x is 2, only Benjamin
is printed. 在此,如果x的值为2,则仅打印Benjamin
。 That's perfectly fine. 很好 Now lets suppose, i change value of x to 3
, not matching any case, than its a fall through from default case
. 现在假设,我将x to 3
值更改x to 3
,不匹配任何大小写,而不是its a fall through from default case
。 Ain't compiler needs to match every case for 3, by that time CASE 2
will be passed, than why it goes back to default and prints hello Benjamin. 到那时CASE 2
将通过时,编译器不需要将每种情况都匹配为3,这比为什么它返回默认值并输出hello Benjamin更为重要。 Can someone explain please? 有人可以解释吗?
Thanks, 谢谢,
You need to add a break;
您需要添加break;
statement to break out of the switch
block. 语句以打破switch
块。
switch (x) {
case 1:
System.out.println("1");
break;
default:
System.out.println("helllo");
break; // <-- add this here
case 2:
System.out.println("Benjamin");
break;
}
Generally speaking, it is also better coding practice to have your default:
case be the last case in the switch
block. 一般而言,最好使用default:
case是switch
块中的最后一个case。
In this case, the switch is following the pattern: 在这种情况下,开关遵循以下模式:
x==1? No, check next case
default? Not done yet, check other cases
x==2? No, check next case
//No more cases, so go back to default
default? Yes, do default logic
// no break statement in default, so it falls through to case 2: logic without checking the case
output case 2 logic
break
Notice how the block will jump over the default case, and save it until a later time unless we have exhausted all other possible cases. 请注意,该块将如何跳过默认情况,并保存到以后,除非我们用尽了所有其他可能的情况。
It prints both strings because you do not have a break
in your default
case, so it continues into case 2
, printing Benjamin. 因为您在default
情况下没有break
,所以它会打印两个字符串,因此它会继续进入case 2
打印Benjamin。 You could fix this by adding a break
or moving case 2
above the default
case. 您可以通过在default
况上方添加break
或将工case 2
移动来解决此问题。
'switch' case is other form of 'if-then-else', the default case is for the final else part. 'switch'大小写是'if-then-else'的其他形式,默认大小写是最后的else部分。 It is advisable to write default at the end of switch. 建议在切换结束时写入默认值。
Default is checked as last. 默认检查为最后。 Thats why it feels like the compiler 'went' back. 这就是为什么感觉编译器“退缩”了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.