Search code examples
javaexceptioninputmismatchexception

InputMisMatch Exception Error


I am trying to code this program that asks the user for the value of x1, and to create an exception if the user inputs something other than an integer. However, when I use the InputMismatchException, I keep getting an error saying that it can not be converted to a throwable?

Here is my code :

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int x1 = getScannerInt("Enter x1");

}

public static int getScannerInt(String promptStr) {
    Scanner reader = new Scanner(System.in);
    int x1 = 1;
    boolean continueLoop = true;
    while (continueLoop) {
        System.out.println("Enter x1: ");
    }
    {
        try {
            x1 = reader.nextInt();
            continueLoop = false;
        } catch (InputMismatchException e) {
            System.out.println("Please only enter numbers");

        }
    }
    return x1;

}

I will appreciate any help!


Solution

  • You have to consume the new line using reader.nextLine(); like this :

    while (continueLoop) {
        System.out.println("Enter x1: ");
        try {
            x1 = reader.nextInt();//this does not consume the last newline
            continueLoop = false;
        } catch (InputMismatchException e) {
            System.out.println("Please only enter numbers");
        }
        reader.nextLine();//You can consume it using nextLine()
    }
    

    Note :

    When you use

    while (continueLoop) 
         System.out.println("Enter x1: ");
    

    the only instruction that work after the while is System.out.println("Enter x1: ");, be careful.