3.6 Choosing From Many Alternatives

Decisions with many possible choices can be handled using nested if statements but Processing has another statement, the switch statement, that often makes choosing from many alternatives an easier task.

Example 1

To see how a switch statement works, suppose that we are writing a program that acts as a simple calculator. If at some point we have two numerical values (operand1 and operand2) and a char variable operator with possible values '+', '-', '*', or '/', then the following fragment will print the value of the corresponding expression.

 

switch (operator)

{

         case '+' : println(operand1 + operand2);

                    break;

         case '-' . println(operand1 - operand2);

                    break;

         case '*' : println(operand1 * operand2);

                    break;

         case '/' : println(operand1 / operand2);

                    break;

}

 

In executing this statement, Processing first determines the value of operator. Then, based on this value, it starts to execute the code inside the brace brackets, starting at the point indicated by the appropriate case. The break; statements cause Processing to stop executing statements inside the switch and to jump down to the point just after the switch. For example, if operand2 = 3, operand2 = 4, and operator = '*', Processing would print the value of 3 * 4 and then exit the switch.

 

In the example, the final break; is not necessary but it is a good programming practice to put it there to make sure that the switch will still work correctly even if, at some later time, an extra case is added to it. As others have noted, a little extra redundancy is often a good idea.

To guard against the possibility that no case matches the value of the expression in the switch, we can (and should) include a default case that contains statements to execute if there is no match. We can also have more than one case value associated with the same statements. Both of these ideas are illustrated in the next example.

 

Example 2

This switch statement assigns a grade based on a quiz that was scored out of five.

 

switch (score)

{

       case 5: grade = 'A';

               break;

       case 4: grade = 'B';

               break;

       case 3: grade = 'C';

               break;

       case 2:

       case 1:

       case 0:  grade = 'F';
                break;

       default: println("Invalid score" + " - grade of ? assigned");

                grade = '?';

                break;

}

 

 

 

In any switch statement, the expression that controls it must have some integer value (byte, short, int, long, or char). This expression is usually simply a variable but it can be an arbitrarily complex expression; the case values, on the other hand, must be constants. The order of the cases is arbitrary. If there is no default case and the value of the expression does not match any of the cases, then the statement does nothing (and Processing gives no error message).

 

 

Exercise 3.6

1.       Rewrite the following using the indentation style shown in the text. 
 
switch(month){case l: case 3:case 5:case 7:case 8:case 10 :case 12:1ength=31;
break;case 4:case 6:case 9:case 11: length=30;break;case 2:if(isLeapYear)length=29;else length=28;break;}
 
2.       a) In Example 1, what would the fragment print if operand1 = 8,    operand2 = 2, and operator = '-'?
       b) What would be printed with these values if there were no break; statements in the switch statement? 
 
 
3.       A sequence of six tests, all scored out of 100, are to be given different weightings in determining
a final mark. Write a program fragment that computes the appropriate weighted score for one test.
The fragment should first read values of testNumber and score.
Using a switch statement, it should then compute and print the appropriate value of
weightedScore using the weightings given in the following table.
 

Test Number

Weight

1

10%

2

20%

3

20%

4

15%

5

15%

6

20%

 
 
       For example, input of 
       3
       27
       Should produce output of
       
A score of 27 on test 3 gives a weighted score of 5.4

4.         Write a program fragment that prints, as a word, the value of the last digit of the int variable number.
            For example, if the value of number is 547, the fragment should print

The last digit of 547 is seven.

   
5.       Write a program that reads a date in numeric form as a year followed by a month followed by a day and
then prints the date as one might on a cheque. For example, input of

 

2000 
7
 1 
should produce output of 
July 1, 2000