CSCI 201 Introduction to Algorithm Design
home | homework index | labs index 
FALL 2006  

Selection Statements

[an error occurred while processing this directive]

In this lab we will finish developing class date. This class actually duplicates class Date that's already built into Java, but this is the best way to illustrate some important ideas.

Multiple selection structure

The switch statement is useful for expressing a certain type of multi-way selection. A switch statement allows you based on the value of an expression jump to some location within the switch statement. The expression must be either integer or character. It cannot be a String or a decimal number.

Example 1:

int n;
.... //some code
switch (n) {   
   case 1:
     System.out.println("The number is 1");
     break;
   case 2:
   case 4:
     System.out.println("The number is 2 or 4");
     break;
   case 3:
     System.out.println("The number is 3");
     break;
   default:
     System.out.println("The number is outside the range 1 to 4");
} 

The break statements are optional. They force flow of control to the end of the switch statement. If you leave out the break statement, the execution of the switch statement will continue.

Leap Year

The specific rules for determining leap years are:

  1. If a year is divisible by 4 it is a leap year if #2 does not apply.
  2. If a year is divisible by 100 it is not a leap year unless #3 applies.
  3. If a year is divisible by 400 it is a leap year.

2004 is a leap year. 1900 is NOT a leap year.

If year is greater than 1752 (Gregorian Calendar) then

   if ((Year % 4 == 0) && ( Year % 100 != 0 || Year % 400 == 0 ))	
      Year is a Leap year

Checkpoint

Answer the questions below. You have to answer all questions correctly to see the rest of the lab.

What value is assigned to price ?

double price;
int code = 2 ; 
switch ( code )
{
  case 1:
    price = 10.10;
    break; 
  case 2:
    price = 10.20;
    break; 
  case 3:
    price = 10.35;
    break; 
  default:
    price = 10.40;
} 

10.10
10.20
10.35
10.40

What is the problem with the following piece of code?

switch(n){ 
	case 1: System.out.println("1 is selected"); 
	case 2: System.out.println("2 is selected"); 
	default: System.out.println("Illegal selection");
} 

More than one message may be displayed
None of the messages will be displayed
Message "1 is selected" will never be displayed
No problems