0

I'm doing exercises related to handling exceptions. While using the Scanner class and following exercises to check for InputMismatchExceptions, I got the following results from the following code.

static Scanner sc = new Scanner(System.in);

public static void main(String[] args){
    System.out.print("Enter an integer: ");
    int a = getInt();
    System.out.print("Enter a second integer: ");
    int b = getInt();
    int result = a + b;
    System.out.println(result);
}

public static int getInt(){
    while (true){
        try {
            return sc.nextInt();
        }
        catch(InputMismatchException e){
            System.out.print("I'm sorry, that's not an integer."
                    + " Please try again: ");
            sc.next();
        }
    }
}

The output was:

Enter an integer: 2 3
Enter a second integer: 5

It seems that if for the first calling of nextInt() I enter "2 3", or two integers with a space between them, the next time that nextInt() is called, it receives the first two integers added together and then halts the program. What is really going on here?

P.S. Does anyone have tips for me in formatting my code in a better way and making it more organized for other coders to read?

Adam Odell
  • 51
  • 4

1 Answers1

1

When you enter "2 3" (Two integers with a space between them) the scanner.nextInt() will pull in the 2 and leave the 3 still in the scanner. Now, when the next nextInt() is called it will pull in the 3 that was left without the user having to enter anymore data.

You can get around this by using nextLine() and check that the input String does not contain spaces.

Something like this:

static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    System.out.print("Enter an integer: ");
    int a = getInt();
    System.out.print("Enter a second integer: ");
    int b = getInt();
    int result = a + b;
    System.out.println(result);
}

public static int getInt() {
    while (true) {
        try {
            String input = sc.nextLine();
            if (!input.contains(" ")) {
                int integer = Integer.parseInt(input);
                return integer;
            } else {
                throw new InputMismatchException();
            }
        } catch (InputMismatchException | NumberFormatException e) {
            System.out.print("I'm sorry, that's not an integer. Please try again: ");
        }
    }
}

Results:

Enter an integer: 2 3
I'm sorry, that's not an integer. Please try again: 2
Enter a second integer: 3
5
Shar1er80
  • 8,751
  • 2
  • 16
  • 25