I want to put a try/catch around the input=scanner.nextInt
to throw an InputMismatchException if a letter is entered, I keep getting an infinite loop. This is the code with the infinite loop. What would be best to fix this?
public void setNumberOfPlayers(Scanner scanner) {
boolean valid = false;
this.numberOfPlayers = 0;
int input = 0;
do {
do {
System.out.println("Please enter the number of players (minimum " + MIN_PLAYERS + " & maximum "
+ MAX_PLAYERS + ".)");
try {
input = scanner.nextInt();
}catch (InputMismatchException e ) {
System.out.println("Please type a numeric digit only");
}
// this.numberOfPlayers = scanner.nextInt();
if (input > MAX_PLAYERS || input < MIN_PLAYERS) {
System.out.println("Invalid input. Enter the number of players");
valid = false;
} else {
this.numberOfPlayers = input;
valid = true;
}
} while (input > MAX_PLAYERS || input < MIN_PLAYERS);
System.out.printf("You have chosen to include %d players. is this correct? (Y/N)", this.numberOfPlayers);
String answer = scanner.next();
switch (answer) {
case "y":
case "Y":
System.out.println("Great - lets start the game with " + this.numberOfPlayers + " players");
valid = true;
break;
case "n":
case "N":
System.out.println("Please re-enter the number of players");
// this.numberOfPlayers = scanner.nextInt();
valid = false;
break;
default:
System.out.println("Please enter a valid response - y / n");
valid = false;
break;
}
} while (!valid);
}