Java Reference
In-Depth Information
The first break statement appears at Line 15, just before the case value of 5 . Even
though the value of the switch expression does not match any of the case values ( 1 , 2 ,
3 ,or 4 ), the statements following these values execute.
When the value of the switch expression matches a case value, all statements execute until
a break is encountered, and the program skips all case labels in between. Similarly, if the
value of num is 3 , it matches the case value of 3 and the statements following this label
execute until the break statement is encountered at Line 15. If the value of num is 9 ,it
matches the case value of 9 . In this situation, the action is empty, because only the break
statement, at Line 24, follows the case value of 9 .
EXAMPLE 4-22
Although a switch structure's case values (labels) are limited, the switch statement
expression can be as complex as necessary. Consider the following switch statement:
switch (score / 10)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
grade = 'F';
break ;
case 6:
grade = 'D';
break ;
case 7:
grade = 'C';
break ;
case 8:
grade = 'B';
break ;
case 9:
case 10:
grade = 'A';
break ;
default :
System.out.println("Invalid test score.");
}
Search WWH ::




Custom Search