Copy/paste this code into a file IfElse.java
:
import java.io.*;
// This program demonstrates if/else statement
// and string comparison
public class IceCream {
public static void main (String [] args) throws IOException {
// set up the reading:
// Create a buffered reader
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// string for storing a line of input
String line; // store input here
String result = new String("Here is your ");
System.out.println("Welcome to our icecream shop!");
// figure out the kind of icecream
System.out.print("Please enter 1 for chocolate, 2 for vanilla: ");
line = in.readLine();
// extract the integer from the entered data:
int kind = Integer.parseInt(line);
if (kind == 1) {
result = result.concat("chocolate icecream");
} else if (kind == 2) {
result = result.concat("vanilla icecream");
} else {
System.out.println("Wrong input. Good bye!");
System.exit(1);
}
// figure out the toping (if any)
System.out.print("Would you like a toping? (Y/N) ");
line = in.readLine();
// compare the string to Y or N
if (line.equals("N")) { // no toping - we are done
result = result.concat("! Please come again!");
} else if (line.equals("Y")) {
// figure out the kind of toping
System.out.print("Please enter 1 for M&Ms, 2 for sprinkles: ");
line = in.readLine();
int toping = Integer.parseInt(line);
if (toping == 1) {
result = result.concat(" with M&Ms! Please come again!");
} else if (toping == 2) {
result = result.concat(" with sprinkles! Please come again!");
} else {
System.out.println("Wrong input. Good bye!");
System.exit(1);
}
} else {
System.out.println("Wrong input. Good bye!");
System.exit(1);
}
// print out the result
System.out.println(result);
}
}
This is an example from CSci 1211 course.