Chapter 17
How to Flick a Virtual Switch
IN THIS CHAPTER
Dealing with many alternatives
Jumping out from the middle of a statement
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 Wayne Brady (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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access