本文共 984 字,大约阅读时间需要 3 分钟。
A switch statement is basically a if, elif, elif, elif, elif, else.
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 statement requires a break.
switch(c){
case('a'){
System.out.println("");
break;}
case('b'){
System.out.println("");
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;
}
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.
转载地址:https://blog.csdn.net/weixin_28875613/article/details/118842704 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!