anonymous
2013-12-27 10:21:00 UTC
additional message, depending on what letter is typed in.For instance,if they
choose ‘A’, your message might be:‘Your prize is a pet aardvark!’ If they choose ‘B’, your message might be ‘Your prize is a pet bear!’and similarly for ‘C’ Modify so that the user can type in any letter from ‘A’ to ‘F’,For this program, you may wish to use the SWITCH statement.
A sample run might look like this: (User input in bold.)
Welcome to the Interrogator.
Choose one of the following letters: A,B, or C: B
Enter your first name: Amir
Enter your age:23
My answer: import java.util.Scanner;
public class Interrogator {
public static void main(String[] args) {
System.out.println("Welcome to Interrogator");
String option = read("Choose one of the following letters: A, B or C: ", "^(?i)[a-c]$");
String name = read("Enter your first name: ", null);
int age = Integer.parseInt(read("Enter your age: ", "^[0-9]{1,3}$"));
System.out.println("Thank you!");
print(option, name, age);
printMessageBy(option);
System.exit(0);
}
private static String read(String message, String constraint) {
boolean done = false;
String result = "";
do {
System.out.print(message);
Scanner keyboard = new Scanner(System.in);
result = keyboard.nextLine();
if (constraint == null || result.matches(constraint)) {
done = true;
} else {
System.out.println("Error: invalid value was entered.");
}
} while (!done);
return result;
}
private static void print(String option, String name, int age) {
System.out.printf("Your name is %s.%n", name);
System.out.printf("You are %d years old.%n", age);
System.out.printf("You have made choice %s.%n", option);
}
private static void printMessageBy(String option) {
if ("A".equalsIgnoreCase(option)) {
System.out.println("Your prize is a pet aardvark!");
} else if ("B".equalsIgnoreCase(option)) {
System.out.println("Your prize is a pet bear!");
} else if ("C".equalsIgnoreCase(option)) {
System.out.println("Your prize is a C!");
}
}
}