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

查看:34
本文介绍了带有字符串错误输出的 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;

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

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