我用java 6写过小代码
public class TestSwitch{
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:{
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
}
case 2:{
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
}
System.out.println("end");
}
}
Output: start 1 2 end
我的编辑器正在显示“案例 3”和“案例 5”的孤立案例。它仍在运行 并显示输出。
Java 中有类似概念的 Nastated cases 吗?
为什么它会给出以上输出?相反,我认为它将是“开始 1 结束”
非常感谢您的回复!!
最佳答案
Switch 替换 if else 但 switch 语法 != If else 语法。
你忘了在每个 case 后面加上 break
。
所以条件落空了。
示例:
case 0:
mColor.setText("#000000");
break;
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
System.out.println(5);
break;
case 7:
System.out.println(7);
break;
default:
System.out.println("nothing");
}
关于java - 无法在 Java 中获取 Switch 案例的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19581953/