sawreals2 sawreals2 - 2 months ago 8
Java Question

Catch Block Not Printing Statement of Invalid Input

I would like for the user to input a number between 0-9. If they enter a number outside of this range (either a negative or a number greater than 9) they have entered an invalid input. Additionally, I would like to use a try catch block to identify an incorrect input type (string), and also print invalid.

There is no need for the user to re-enter input. Once is fine.

What I have tried so far:

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Random;

public class guessinggame
{
public static void main (String[] args)
{
int randomNumber = new Random().nextInt(10);
System.out.println("My number is " + randomNumber + ". ");

System.out.println("I’m thinking of a number between 0 and 9.");
System.out.println("What is your guess:");


Scanner keyboard = new Scanner(System.in);
int guess = keyboard.nextInt();

try{
input = keyboard.nextInt();

}catch (InputMismatchException e){
guess = keyboard.nextInt();
System.out.println("Invalid.");
}



if (guess < randomNumber) {
System.out.println("your guess was too low.");
}else if (guess > randomNumber){
System.out.println("your guess was too high.");
}else if (guess == randomNumber){
System.out.println("your guess was correct.");
}else if (guess < 0){
System.out.println("Invalid.");
}else if (guess > 9){
System.out.println("Invalid.");
}
}
}


Here is only my try catch block:

try{
input = keyboard.nextInt();

}catch (InputMismatchException e){
guess = keyboard.nextInt();
System.out.println("Invalid.");
}


The problem I have is, when compiled, and I enter a string input such as "abc", the program creates a run time error of this format:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at guessinggame.main(guessinggame.java:17)


When instead all that should be displayed after entry of a string is:
Invalid.
as per the statement
System.out.println("Invalid.");
in my catch block.

Answer

Your error is being thrown on this line: int guess = keyboard.nextInt();, which is not surrounded by a try/catch statement. Just so you know, each time you call Scanner.nextInt(), you are asking for a new line. Try doing this:

int guess = -1; // This will be an invalid input
try{
    guess = keyboard.nextInt();
}catch (InputMismatchException e){
    // Because guess is already -1, "invalid" will be printed out by 
    // Below if statements
}

This way, if the user enter an invalid guess, you use your already created if statements to handle it.