import java.io.*;
// This program demonstrates switch statement
// Switch works only for integers or characters
public class SwitchTest {
public static void main (String [] args) throws IOException {
// Create a buffered reader
// need only one buffered reader for all your reading
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// string for storing a line of input
String line;
// prompt the user:
System.out.println("Which icecream would you like? Please enter");
System.out.print("1 for vanilla, 2 for chocolate, 3 for strawberry: ");
// read a line of input:
line = in.readLine();
// extract the integer from the entered data:
int n = Integer.parseInt(line);
String flavor = new String();
switch(n) {
case 1:
flavor = new String(" vanilla ");
break;
case 2:
flavor = new String(" chocolate ");
break;
case 3:
flavor = new String(" strawberry ");
break;
default:
System.out.println("Wrong input");
System.exit(1);
}
// prompt the user:
System.out.println("Which topping would you like? Please enter");
System.out.print("M for M&Ms, S for sprinkles, C for chocolate chips");
// read a line of input:
line = in.readLine();
// extract the integer from the entered data:
char c = line.charAt(0);
String topping = new String();
switch(c) {
case 'M': case 'm':
topping = new String(" M&Ms ");
break;
case 'S': case 's':
topping = new String(" sprinkles ");
break;
case 'C': case 'c':
topping = new String(" chocolate chips ");
break;
default:
System.out.println("Wrong input");
System.exit(1);
}
System.out.println("Here is your" + flavor +
"icecream with" + topping);
}
}
This is an example from CSci 1211 course.