The Conditional Operator and the 'switch' Statement
10. Corrected Program
Answer:
The correct program fragment is given below.
Corrected Program
break
after the statement in the default case, but it is not needed.
class Switcher{ public static void main ( String[] args ) { char color = 'Y' ; String message = "Color is"; switch ( color ) { case 'R': message = message + " red" ; break; case 'O': message = message + " orange" ; break; case 'Y': message = message + " yellow" ; break; case 'G': message = message + " green" ; break; case 'B': message = message + " blue" ; break; case 'V': message = message + " violet" ; break; default: message = message + " unknown" ; } System.out.println ( message ) ; } } |
Often what you really want is for several characters to select a single case. This can be done using several case statements, followed by just one list of statements.
For example, here both 'y' and 'Y' select the same statement:
case 'y': case 'Y': message = message + " yellow" ; break;
Question 10:
Mentally insert extra case statements into the program so that upper and lower case
characters work for each color. (Or, even better: copy the program to an editor, fix it, and run it.)