Help with switch statement
I am relatively new to java. In a switch
stateme开发者_如何转开发nt, do you have to put a break
statement after each case
?
No, you don't have to. If you omit the break
statement, however, all of the remaining statements inside the switch
block are executed, regardless of the case
value they are being tested with.
This can produce undesired results sometimes, as in the following code:
switch (grade) {
case 'A':
System.out.println("You got an A!");
//Notice the lack of a 'break' statement
case 'B':
System.out.println("You got a B!");
case 'C':
System.out.println("You got a C.");
case 'D':
System.out.println("You got a D.");
default:
System.out.println("You failed. :(");
}
If you set the grade
variable to 'A', this would be your result:
You got an A!
You got a B.
You got a C.
You got a D.
You failed. :(
You don't have to break after each case, but if you don't they will flow into each other. Sometimes you want to bundle multiple cases together by leaving out the breaks.
It is better you do. Otherwise the next statements will be executed too.
switch(someNumber) {
case thisCaseMatches:
doThat();
case thisCaseDoesNotMatch:
shouldntExecuteYetItWillBeExecuted();
default:
alsoWillbeExecuted();
}
You do if you are not exiting the switch
statement with a return
or other action.
Semantically yes. Otherwise all case statements after the first matching one would run.
It's a good practice to put break after each statement.
You're not forced.
But if you don't put breaks tatement you've cascade switch statement, namely more condition could be matched, and sometimes this can lead to logical errors.
However there are people which think that cascade statements can optimize the code, helping to write less code.
精彩评论