带有字符串错误输出的 switch 语句
我遇到了这个基本问题,其中 switch case 与字符串一起使用.
I came across this basic question, where switch case is used with string.
Break 语句在 case 之间不使用,但为什么即使它与 case 字符串不匹配,它也会对所有 case 进行?
Break statement is not used between cases but why it going to all the cases even when it is not matching the case string?
所以我很想知道为什么输出是 3 而不是 1?
public static void main(String [] args)
{
int wd=0;
String days[]={"sun","mon","wed","sat"};
for(String s:days)
{
switch (s)
{
case "sat":
case "sun":
wd-=1;
break;
case "mon":
wd++;
case "wed":
wd+=2;
}
}
System.out.println(wd);
}
推荐答案
你在 case "mon"
的末尾没有 break;
所以 value 是也增加了 2
You don't have a break;
at the end of case "mon"
so value is also incremented by 2
你没想到的,流:
0 -1 -1 +1+2 +2 = 3
^ ^ ^ ^ ^
init sat sun mon wed
添加如下中断将导致输出 1
Adding a break as below will result with output 1
case "mon":
wd++;
break;
相关文章