带有错误输出的switch语句 [英] Switch statement with string wrong output

查看:111
本文介绍了带有错误输出的switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个基本问题,即将开关大小写与字符串一起使用.

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

在案例之间不使用break语句,但是为什么即使不匹配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);
      }

推荐答案

在情况"为"mon" 的末尾,您没有 break; ,因此值是也增加了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;

这篇关于带有错误输出的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆