为什么 java 在 switch 语句中需要中断?
switch 语句基本上是 if、elif、elif、elif、elif、else.
A switch statement is basically a if, elif, elif, elif, elif, else.
为什么 switch 语句需要一个 break 而 else if 语句不需要?有什么区别?
Why does a switch statement need a break within it and an else if statement doesnt? What is the difference?
如果,否则如果不需要休息.
If, else if doesn't require a break.
if (c = 'a'){
System.out.println("");
}
else if (c = 'b'){
System.out.println("");
}
Switch 语句需要中断.
Switch statement requires a break.
switch(c){
case('a'){
System.out.println("");
break;}
case('b'){
System.out.println("");
break;}
}
推荐答案
你必须在每个案例中添加 break
,例如
You have to add break
to each case, e.g.
switch(choice){
case 1:
System.out.print("haha");
break;
case 2:
System.out.print("aloha");
break;
}
每个 break 语句都会终止封闭的 switch 语句.控制流继续 switch 块之后的第一条语句.break 语句是必要的,因为没有它们,switch 块中的语句就会失败:匹配的 case 标签之后的所有语句都按顺序执行,无论后续 case 标签的表达式如何,直到遇到 break 语句.
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. 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.
相关文章