go to previous page   go to home page   go to next page highlighting

(Trick Question:) What would be the discount if code were 'a' ?

Answer:

0.3

Notice that the code is a lower case 'a', not upper case.


Using 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.

Examine the following fragment:

The fragment will print:

Color is yellow green blue violet unknown

This is probably not what the program was intended to do.


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.


go to previous page   go to home page   go to next page