I'm new in Java and have a problem after catching an exception. After catching an exception the program ends, but i want to continue the loop. The use of the program is that a user type in numbers between 1 and 10 through a scanner until the typed number is equal to the random number defined before.
public class GuessingGame {
public static void main(String[] args) {
System.out.println("Welcome!");
int min = 1;
int max = 1000;
int randomNumber = (int) (Math.random() * (max - min) + 1) + min;
Scanner scanner = new Scanner(System.in);
int firstDraw = 1;
int maxDraw = 1000;
try {
while (firstDraw < maxDraw) {
System.out.println("Please enter your guess: ");
int guessingNumber = scanner.nextInt();
if (guessingNumber < randomNumber) {
System.out.println("Too small!");
} else if (guessingNumber > randomNumber) {
System.out.println("Too big!");
} else {
System.out.println("You win");
}
firstDraw++;
}
} catch (InputMismatchException e){
System.out.println("Not a number - try again!");
}
}
}
I guess the problem is, where im going to place the try-catch block. I tried several possibilities but i dont get the right solution. If I just type in numbers, the program works and it ends until i guessed the right number. But if i use letters instead of numbers, it ends the program. I also saw some similiar problems asked before but i really don't get it
Thy for your help fellows :)
"... After catching an exception the program ends, but i want to continue the loop. ..."
Use the Scanner#next, and Integer#parseInt, methods.
And, place the try-catch within the loop.
Additionally, when the correct value is guessed, break the loop.
Note that the parseInt method throws a NumberFormatException, and not a InputMismatchException.
while (firstDraw < maxDraw) {
System.out.println("Please enter your guess: ");
try {
int guessingNumber = Integer.parseInt(scanner.next());
if (guessingNumber < randomNumber) {
System.out.println("Too small!");
} else if (guessingNumber > randomNumber) {
System.out.println("Too big!");
} else {
System.out.println("You win");
break;
}
firstDraw++;
} catch (NumberFormatException e){
System.out.println("Not a number - try again!");
}
}
Output
Welcome!
Please enter your guess:
abc
Not a number - try again!
Please enter your guess:
123
Too small!
Please enter your guess:
456
Too big!
Please enter your guess:
241
You win
On a final note, you can utilize the RandomGenerator#nextInt method, to specify a bounds.
int randomNumber = new Random().nextInt(min, max + 1);