Wednesday, December 10, 2008

Pulling a Switcheroo

Pulling a Switcheroo

In Book II, Chapter 4, you find out about the workhorses of Java decision-making: boolean expressions and the mighty if statement. In this chapter, you discover another Java tool for decision making: the switch statement. The switch statement is a pretty limited beast, but it excels at one particular type of decision making: choosing one of several actions based on a value stored in an integer variable. As it turns out, the need to do just that comes up a lot. So you want to keep the switch statement handy when such a need arises.

else-if Monstrosities

Many applications call for a simple logical selection of things to be done depending on some value that controls everything. As I describe in Book II, Chapter 4, such things are usually handled with big chains of else-if statements all strung together.

Unfortunately, these things can quickly get out of hand. else-if chains can end up looking like DNA double-helix structures, or those things that dribble down from the tops of the computer screens in The Matrix.

For example, Listing 6-1 shows a bit of a program that might be used to decode error codes in a Florida or Ohio voting machine.

Listing 6-1: The else-if Version of the Voting Machine Error Decoder
Image from book

import java.util.Scanner;

public class VoterApp
{

static Scanner sc = new Scanner(System.in);

public static void main(String[] args)
{

System.out.println
("Welcome to the voting machine "
+ "error code decoder.\n\n"
+ "If your voting machine generates "
+ "an error code,\n"
+ "you can use this program to determine "
+ "the exact\ncause of the error.\n");
System.out.print("Enter the error code: ");
int err = sc.nextInt();

String msg;
if (err==1)
msg = "Voter marked more than one candidate.\n"
+ "Ballot rejected.";
else if (err==2)
msg = "Box checked and write-in candidate "
+ "entered.\nBallot rejected.";
else if (err==3)
msg = "Entire ballot was blank.\n"
+ "Ballot filled in according to "
+ "secret plan.";
else if (err==4)
msg = "Nothing unusual about the ballot.\n"
+ "Voter randomly selected for tax audit.";
else if (err==5)
msg = "Voter filled in every box.\n"
+ "Ballot counted twice.";
else if (err==6)
msg = "Voter drooled in voting machine.\n"
+ "Beginning spin cycle.";
else if (err==7)
msg = "Voter lied to pollster after voting.\n"
+ "Voter's ballot changed "
+ "to match polling data.";
else
msg = "Voter filled out ballot correctly.\n"
+ "Ballot discarded anyway.";
System.out.println(msg);
}
}
Image from book

Wow! And this program has to decipher just seven different error codes. What if the machine had 500 different codes?

No comments:

Post a Comment