• No results found

The switch construct

if(age == 12)

System.out.println("You are 12");

else if(age == 13)

System.out.println("You are 13");

else if(age == 14)

System.out.println("You are 14");

else

System.out.println("You not 12, 13, or 14");

In the preceding code fragment, the last if println() statement executes only if all the preceding if statements have evaluated to false. If one of the if statements evaluates to true, then the rest of the construct is skipped.

In some cases, several logical variations of the consecutive if statements may produce the desired results, while in other cases it may not.

Flowcharting is an effective way of resolving doubts about program logic.

The else-if is a mere convenience. The same action results if the else and the if clause are separated. For example:

if(age == 12)

System.out.println("You are 12");

else

if(age == 13) . . .

The switch construct

It is a common programming technique to use the value of an integer vari-able to direct execution to one of several processing routines. You have probably seen programs in which the user selects among several process-ing options by enterprocess-ing a numeric value, as in the followprocess-ing example:

***********************************

| PAYROLL DATA PROCESSING |

| ROUTINE |

***********************************

| Options: |

| 1. enter new employee |

| 2. calculate payroll |

| 3. delete employee |

| 4. enter employee data |

***********************************

| Enter option number: |

***********************************

When using this menu, the user enters an integer value for selecting the desired processing option in the payroll program. One way of implement-ing a menu selection is to use several consecutive if statements to test the value of the input variable. The Java switch construct provides an alterna-tive mechanism for selecting among multiple options. The switch con-sists of the following elements:

1. The switch keyword

2. A controlling expression enclosed in parentheses. Must be of integer type.

3. One or more case statements followed by an integer or character constant, or an expression that evaluates to a constant. Each case statement termi-nates in a colon symbol.

4. An optional break statement at the end of each case block. When the break is encountered, all other case statements are skipped.

5. An optional default statement. The default case receives control if none of the other case statements have executed.

The switch construct provides a simple alternative to a complicated if, else-if, and else chain. The general form of the switch statement is as fol-lows:

statement;

. . . [break;]

}

Incidentally...

The preceding example uses a non-existent computer language, called pseudocode. Pseudocode shows the fundamental logic of a pro-gramming construct, without complying with the formal require-ments of any particular programming language. There are no strict rules to pseudocode; the syntax is left to the programmer's imagina-tion. The preceding pseudocode listing combines elements of the Java language with symbols that are not part of Java. For example, the ...

characters (called ellipses) indicate that other program elements could follow at this point. The bracket symbols are used to signal op-tional components.

The controlling expression of a switch construct follows the switch keyword and is enclosed in parentheses. The expression, usually a vari-able, must evaluate to an integer type. It is possible to have a controlling expression with more than one variable, one that contains literal values, or to perform integer arithmetic within the controlling expression.

Each case statement marks a position in the code. If the case state-ment is true, execution continues at the code that follows the case key-word. The case keyword is followed by an integer or character constant, or an expression that evaluates to an integer or character constant. The case constant is enclosed in single quotation symbols (tic marks) if the control statement is a char type. The following code fragment shows a case construct in which the switch variable is of type char.

char charVar;

. . .

switch (charVar) {

case 'A':

System.out.println(“Input was A”);

break;

case 'B':

System.out.println(“Input was B”);

break;

. . . }

The case constant does not require tic marks when the control state-ment evaluates to an int type. The following code fragstate-ment shows a case construct in which the switch variable is of type int.

int intVar;

The break keyword is optional, but if it is not present at the end of a case block, then the following case or default blocks execute. In other words, execution in a switch construct continues until a break keyword or the end of the construct is encountered. When a break keyword is en-countered, execution is immediately directed to the end of the switch construct. A break statement is not required on the last block (case or de-fault statement), although the break is usually included to make the code easier to read.

The blocks of execution within a switch construct are enclosed in ros-ters; however, the case and the default keywords automatically block the statements that follow. Rosters are not necessary to indicate the first-level execution block within a case or default statement.

The following program shows the processing necessary for implement-ing menu selection usimplement-ing a Java switch construct.

On the Web

The MenuDemo.java program is found in the Chapter 9 folder at www.crcpress.com.

// File name: MenuDemo.java // Reference: Chapter 9 //

// Java program to demonstrate menu selection // Topics:

// 1. Using the switch construct //

// Requires:

// 1. Keyin class in the current directory

public class MenuDemo {

public static void main(String[] args) {

// Local variable int swValue;

// Display menu graphics

System.out.println("============================");

System.out.println("| MENU SELECTION DEMO |");

System.out.println("============================");

System.out.println("| Options: |");

System.out.println("| 1. Option 1 |");

System.out.println("| 2. Option 2 |");

System.out.println("| 3. Exit |");

System.out.println("============================");

swValue = Keyin.inInt(" Select option: ");

// Switch construct

break; // This break is not really necessary }

} }

Related documents