I would like the program to re-do the while loop when it catches the exception - the exception being receiving a text input. Instead it continues a while loop with the code below, I would like it to ask for the user input again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int between = 100;
int secretNumber = (int)(Math.random()*between);
int inputNum = 0;
int guesses = 0;
System.out.println("Please enter your guess: ");
inputNum = Scanner.nextInt();
guesses++;
// #### Loop here ####
while (inputNum != secretNumber) {
// Try catch
try {
// number too high or too low
if (inputNum > 100 | inputNum < 0) {
System.out.println("Please enter a guess between 0 and " + between + ".");
inputNum = Scanner.nextInt();
}
// less than secretNumber
if (inputNum < secretNumber) {
System.out.println("Try higher");
inputNum = Scanner.nextInt();
guesses++;
}
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Try lower");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
}
}
System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses + " guesses.");
}
}
Output:
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher