0

Why input.nextLine() keeps running the catch block when I'm inputting a value which is not an integer? And why it is not running from input.nextInt when I'm inputting an Int value in input.nextLine()?

import java.util.InputMismatchException;
import java.util.Scanner;
    public class ExceptionHandlingEg01 {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int num = 0;
            do{
                try{
                    num = input.nextInt();
                    if(num != -1) {
                        System.out.println("You Entered " + num + "\nEnter -1 to exit: ");
                    }
                    else {
                        System.out.println("Program Exited");
                    }
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                    System.out.println("Please Enter a number");
                    input.nextLine();
                }
            } while (num != -1);
        }
    }

1 Answers1

0

Your code moves to the catch block because your code requested an integer, but you didn't enter an integer. This is normal and expected behaviour.

It looks like you may have mis understood how the catch block works. Here is a correctly functioning version of your code that asks for a number at the start of your do/while loop:

Scanner input = new Scanner(System.in);
int num = 0;
do{
    //Move the question to the top of the loop
    System.out.println("Please Enter a number");
    try{
        num = input.nextInt();
        if(num != -1) {
            System.out.println("You Entered " + num + "\nEnter -1 to exit: ");
        }
        else {
            System.out.println("Program Exited");
        }
    }
    //This will only be called if an invalid input is entered
    //Once the catch block is complete the loop will run again and ask for another number
    catch (InputMismatchException e) {
        e.printStackTrace();
        //Print the fail message here
        System.out.println("That was not a number");

        //The below line was removed, this is not the correct place for it. The loop already reads the number at the start
        //input.nextLine();
    }
} while (num != -1);

Caution: Be very careful when using next methods like nextInt() with nextLine(), your code will not read correct inputs, see here for more information: Scanner is skipping nextLine() after using next() or nextFoo()?

sorifiend
  • 5,927
  • 1
  • 28
  • 45