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 语句


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01