Switch statement with string wrong output

青春壹個敷衍的年華 提交于 2021-02-05 08:31:31

问题


I came across this basic question, where switch case is used with string.

Break statement is not used between cases but why it going to all the cases even when it is not matching the case string?

So I'm curious to know why is the output 3 and not 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);
      }

回答1:


You don't have a break; at the end of case "mon" so value is also incremented by 2

which you didn't expect, flow:

0    -1   -1   +1+2  +2 = 3
^     ^    ^   ^     ^
init sat  sun  mon  wed 

Adding a break as below will result with output 1

case "mon":
  wd++;
  break;



回答2:


There is no break; at the end of cases for "sat" and "mon". This means that when an element matches "sat" and "mon" case it will execute the code contained in that case but then fall into the next case.

When the break is reached, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block.

In this instance. When it tests "sat" and "mon", it does not see a break and therefore continues testing.

0   -1    0    2    4    3
^    ^    ^    ^    ^    ^
    sun  mon  mon  wed  sat


来源:https://stackoverflow.com/questions/55514434/switch-statement-with-string-wrong-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!