Chapter 11

How to Flick a Virtual Switch

IN THIS CHAPTER

check Dealing with many alternatives

check Jumping out from the middle of a statement

check 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 (the show’s host) needs is Java’s switch statement.

Meet the switch Statement

The code in Listing 9-2 (refer to 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 myRandom.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 ...

Get Beginning Programming with Java For Dummies, 5th 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.