Chapter 11

How to Flick a Virtual Switch

In This Chapter

arrow Dealing with many alternatives

arrow Jumping out from the middle of a statement

arrow Handling alternative assignments

Imagine playing Let’s Make a Deal with ten different doors. “Choose door number 1, door number 2, door number 3, door number 4. . . . Wait! Let’s break for a commercial. When we come back, I’ll say the names of the other six doors.”

What Monty Hall needs is Java’s switch statement.

Meet the Switch Statement

The code in Listing 9-2 in Chapter 9 simulates a fortune-telling toy — an electronic oracle. Ask the program a question, and the program randomly generates a yes or no answer. But, as toys go, the code in Listing 9-2 isn’t much fun. The code has only two possible answers. There’s no variety. Even the earliest talking dolls could say about ten different sentences.

Suppose that you want to enhance the code of Listing 9-2. The call to my Random.nextInt(10) + 1 generates numbers from 1 to 10. So maybe you can display a different sentence for each of the ten numbers. A big pile of if statements should do the trick:

if (randomNumber == 1) {

    System.out.println(“Yes. Isn’t it obvious?”);

}

if (randomNumber == 2) {

    System.out.println(“No, ...

Get Beginning Programming with Java® For Dummies®, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.