Rob B.
Rob B.

Reputation: 5

Scanner Try Catch Statement results in java.util.InputMismatchException

Why is my code giving me an error? If the user entered a wrong number shouldn't the code let me enter a new valid number? Seems as though it doesn't let me change favorite to a new value. How could I get around this problem?

package RobB;

import java.util.Scanner;

public class FavoriteNum {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[] num = new int[10];
        int favorite = 0;

        System.out.print("Enter your favorite number: ");
        try {
            favorite = scan.nextInt();
        }
        catch (Exception e) {
            System.out.println("Enter an integer!");
            System.out.print("Enter your favorite number: ");

            favorite = scan.nextInt();
        }

        for (int i = 0; i < 10; i++) {
            System.out.print("Enter a random number (" + Math.abs(((i + 1) - 10)) + " to go): ");
            num[i] = scan.nextInt();
        }
    }
}

Console output:

Enter your favorite number: 11.1

Enter an integer!

Exception in thread "main" Enter your favorite number: java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at RobB.FavoriteNum.main(FavoriteNum.java:21)

Upvotes: 0

Views: 61

Answers (2)

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

Scanning for input in catch clause seems to be not the best idea. I would suggest using a do-while loop and the condition allowing to leave this loop could be a boolean flag which state would be changed when you confirmed that the valid Integer has been finally entered. You might also want to consider using Scanner's hasNextInt() method to check if the correct input has been provided, without throwing any exception if it is not really necessary in you case. Here is a little variation of ronhash's answer, but using a do-while loop:

boolean validInput = false;
do {
    try {
        System.out.print("Enter your favourite number: ");
        favorite = scan.nextInt();
        validInput = true; }
    catch (Exception e) {
        System.out.println("Enter an integer!"); }
} while (!validInput)

Edit: I edited the code because the previous one was inneficient and wrong.

Upvotes: 0

ronhash
ronhash

Reputation: 874

This is an alternative with a while loop:

boolean validInput = false;
while (!validInput) {
   try {
        System.out.print("Enter your favourite number: ");
        favorite = scan.nextInt();
        validInput = true;
    }
    catch (Exception e) {
        System.out.println("Enter an integer!");
    }
}

Upvotes: 1

Related Questions