无法在java中获取Switch案例的行为 [英] Unable to get behaviour of Switch case in java
问题描述
我在java 6中编写了小代码
I have written small code in 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");
}
}
输出:开始1 2结束
我的编辑器显示案例3的孤立案例和'案例5'。它仍然运行
并显示输出。
My editor is showing orphaned case for 'case 3' and 'case 5'.Still it is running and showing output.
- 在Java中是否存在类似概念的Nastated案例?
-
为什么要提供以上输出?相反,我认为这将是'开始1结束'
- Does Nastated cases like concept is there in Java?
And Why it is giving above output? rather i thought it will be 'start 1 end'
您的回复将不胜感激!!
Your response will be greatly appreciated!!
推荐答案
切换替换if else但切换语法!= If else语法。
在每个案例之后你忘记了 break
。
You forgot to put break
after each case.
因此下的条件下降通过。
示例:
case 0:
mColor.setText("#000000");
break;
中断语句是必要的,因为如果没有它们,switch块中的语句将会失败:匹配的case标签之后的所有语句将按顺序执行,而不管后续case标签的表达式如何,直到遇到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中获取Switch案例的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!