I'm making a small word game which requires the user to choose from options 1 to 3, 1 and 2 being a game and 3 being exit. I have the error handling set for the correct integer but not sure why the program crashes when the user inputs something thats not an integer.
import java.util.Scanner;
public class Small_Programming_Assignment {
public static void main(String[] args) {
getSelection();
substringProblem();
pointsProblem();
}
public static void getSelection() {
Scanner sc = new Scanner(System.in);
System.out.println("");
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
int choice = sc.nextInt();
if (choice == 1) {
substringProblem();
}
else if (choice == 2) {
pointsProblem();
}
else if (choice == 3) {
System.out.println("Goodbye!");
System.exit(0);
}
else if (!sc.hasNextInt() ) {
System.out.println("Invalid option. Try again.");
getSelection();
} else {
System.out.println("Invalid option. Try again.");
getSelection();
}
}
public static void substringProblem() {
System.out.println("Substring Problem");
getSelection();
}
public static void pointsProblem() {
System.out.println("Points Problem");
getSelection();
}
}
I'm trying to uses (!sc.hasNextInt() ) but it seems the program crashes before reaching this.
CodePudding user response:
As far as I see, whenever I type in a value that's not an Integer, the program throws a Runtime Exception called InputMismatchException
.
According to Oracle's Java documentation:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
The program doesn't reach your "Invalid option. Try again." statement, because the exception is thrown directly after the user input, which means, you can't provide anything other than an integer through Scanner
's nextInt()
method.
What you could do, if you still want to use this method, would be placing it in a try/catch
statement, something like below:
int choice = 0;
try {
choice = sc.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Invalid option. Try again.");
getSelection();
}
if (choice == 1) {
substringProblem();
}
else if (choice == 2) {
pointsProblem();
}
else if (choice == 3) {
System.out.println("Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid option. Try again.");
getSelection();
}
This should do the job. Now, whenever a user is typing something that cannot be parsed as an Integer, the runtime exception is thrown, is caught, so the program enters the catch
block, outputs "Invalid option. Try again." and "re"-calls getSelection()
.