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:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01