Page 156 - Introduction to Programming with Java: A Problem Solving Approach
P. 156
122 Chapter 4 Control Statements
/****************************************************************
*
ZipCode.java
Dean & Dean
This program identifies geographical region from ZIP code.
******************************************************************/
*
*
*
import java.util.Scanner;
public class ZipCode
{
}
// end class ZipCode
public static void main(String[] args)
{
}
// end main
Scanner stdIn = new Scanner(System.in);
String zip; // user-entered ZIP code
System.out.print("Enter a ZIP Code: ");
zip = stdIn.nextLine();
switch (zip.charAt(0))
{
}
case '4': case '5': case '6':
System.out.println(
zip + " is in the Central Plains area.");
break;
case '7':
System.out.println(zip + " is in the South.");
break;
case '8': case '9':
System.out.println(zip + " is in the West.");
break;
default:
System.out.println(zip + " is an invalid ZIP Code.");
// end switch
case '0': case '2': case '3':
System.out.println(zip + " is on the East Coast.");
break;
Apago PDF Enhancer
Figure 4.9 Using a switch statement to find geographical region from ZIP Code switch Statement Versus “if, else if” Form of the if Statement
Now you know that the switch statement allows you to do one or more things from a list of multiple possibilities. But so does the “if, else if” form of the if statement, so why would you ever use a switch statement? Because the switch statement provides a more elegant solution (cleaner, better-looking organi- zation) for certain kinds of problems.
Now for the opposite question: Why would you ever use the “if, else if” form of the if statement rather than the switch statement? Because if statements are more flexible. With a switch statement, each test