Switch statement with string wrong output(带有字符串错误输出的 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 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有字符串错误输出的 switch 语句
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
