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.