I am new to java and am trying to add error handling to my projects. In this number generator, I want to add a try catch function to catch exceptions from not entering a number. I have read other people's try catch options and pasted my code in their loops, however my code either:
1) Is stuck repeating code in catch block
2) Performs code in catch block and ends without repeating loop
I have tried countless edits to fix this but I keep getting one of those two results :( Thank you for any help!
(This code repeats catch block print message)
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(21);
int guess = -1;
System.out.print("Guess a number between 0 and 20: ");
do {
try {
guess = input.nextInt();
if (guess > number)
System.out.print("Number is too high! ");
else if (guess < number)
System.out.print("Number is too low! ");
else {
System.out.print("That's correct! ");
System.out.printf("My number was %d!", number);
}
} catch (InputMismatchException e) {
System.out.println("That's not a number!");
}
} while (guess != number);
}
}