Johny Nassar
Johny Nassar

Reputation: 41

Can't enter the NumberFormatException

I was trying to write a program that prompts the user to read two integers and displays their sum and my program should prompt the user to read the number again if the input is incorrect. That's what I came up with:

import java.util.*;
public class NumFormatException {

    public static void main(String[] args) throws NumberFormatException {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter 2 integers: ");
        int num1=0;
        int num2=0;


            boolean isValid = false;

            while (!isValid)  {
            try
            {
                num1=input.nextInt();
                num2=input.nextInt();
                isValid=true;
            }
            catch(NumberFormatException ex)
            {
                System.out.println("Invalid input");
            }
        }
            System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
    }

}

My main goal is to put the user in a situation to re-enter an integer if the input is incorrect. When I enter two integers, operation work well but my problem is with the exception: when I enter for example a instead of an integer, my program crashed.

Upvotes: 0

Views: 314

Answers (1)

Mureinik
Mureinik

Reputation: 311843

There are two problems here. First, If a nextXYZ method of Scanner encounters a wrong input, it won't throw a NumberFormatException but an InputMismatchException. Second, if such an exception is thrown, the input token won't be consumed, so you need to consume it explicitly again:

try {
    num1=input.nextInt();
    num2=input.nextInt();
    isValid=true;
} catch (InputMismatchException ex) { // catch the right exception
    System.out.println("Invalid input");
    // consume the previous, erroneous, input token(s)
    input.nextLine();
}

Upvotes: 2

Related Questions