Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)

7.6 The Case Statement

As mentioned in Chapter 6, the case structure is an expanded selection structure because it has more than two alternate paths. The case statement tests the value of a variable of type integer or of type character. Depending on the value of this variable, the statement selects the appropriate path to follow.

The variable to test is called the selector variable. The general structure of the case statement is:

case 〈 selector_variable 〉 of value sel_variable_value : 〈 statements 〉 ... endcase

The following example, which is widely known among students, determines the numeric value of the letter grades. Assume the possible letter grades are A, B, C, D, and F, and the corresponding numerical grades are 4, 3, 2, 1, and 0. The following case statement first evaluates the letter grade in variable letter_grade and then, depending on the value of letter_grade, it assigns a numerical value to variable num_grade.

case letter_grade of value 'A' : num_grade = 4 value 'B' : num_grade = 3 value 'C' : num_grade = 2 value 'D' : num_grade = 1 value 'F' : num_grade = 0 endcase

The example assumes that the variables involved have an appropriate declaration, such as:

variables integer num_grade character letter-grade ...

For the next example, consider the types of tickets for the passengers on a ferry. The type of ticket determines the passenger class. Assume that there are five types of tickets, 1, 2, 3, 4, and 5. The following case statement displays the passenger class according to the type of ticket, in variable ticket-type.

variables integer ticket_type ... case ticket-type of value 1: print "Class A" value 2: print "Class B" value 3: print "Class C" value 4: print "Class D" value 5: print "Class E" endcase

The case statement supports compound statements, that is, multiple statements instead of a single statement in one or more of the selection options.

Another optional feature of the case statement is the default option. The keywords default or otherwise can be used for the last case of the selector variable. For example, the previous example only took into account tickets of type 1, 2, 3, 4, and 5. This problem solution can be enhanced by including the default option in the case statement:

case ticket_type of value 1: print "Class A" value 2: print "Class B" value 3: print "Class C" value 4: print "Class D" value 5: print "Class E" otherwise display "Rejected" endcase

Категории