The Conditional Operator and the 'switch' Statement
9. Using break
Answer:
0.3
Notice that the code is a lower case 'a', not upper case.
Using break
break
There is one label per case
statement, and there must be an exact match with the expression in the switch
for the case to be chosen.
The break
at the end of each case
is optional. If it is omitted, then after the statements in the selected case have executed, execution will continue with the following case. This
is not usually what you want.
The fragment will print:
Color is yellow green blue violet unknown
This is probably not what the program was intended to do.
Examine the following fragment:
class Switcher { public static void main ( String[] args ) { char color = 'Y' ; String message = "Color is"; switch ( color ) { case 'R': message = message + " red" ; case 'O': message = message + " orange" ; case 'Y': message = message + " yellow" ; case 'G': message = message + " green" ; case 'B': message = message + " blue" ; case 'V': message = message + " violet" ; default: message = message + " unknown" ; } System.out.println ( message ) ; } } |
Question 9:
Mentally fix the program fragment so that it prints just one color name.