Search code examples
javajava.util.scannerinputmismatchexception

InputMismatchException when entering integers multiple times


I have seen other similar questions and didn't find any solution to my problem.

Just trying to scan 2 numbers and add them together:

Scanner input = new Scanner(System.in);
int number1;
int number2;
int sum;

System.out.print("First: ");
number1 = input.nextInt();
System.out.println("Second: ");
number2 = input.nextInt();

sum = number1 + number2;

System.out.println("The sum is " + sum);

the first one is printed out nicely and the next time it just crashes with IME... What am i doing wrong?


Solution

  • This question has been asked many times here including myself long ago.

    When using scn.nextInt(), it still waits from input thus affecting all the inputs later on.

    There are 2 approach to solve this problem.

    1. Place a scn.nextLine() after your scn.nextInt();

      System.out.print("First: ");
      number1 = input.nextInt(); input.nextLine();
      System.out.println("Second: ");
      number2 = input.nextInt(); input.nextLine();
      
    2. Receive as String and parse to integer (I prefer this method)

      System.out.print("First: ");
      number1 = Integer.parseInt(input.nextLine());
      System.out.println("Second: ");
      number2 = Integer.parseInt(input.nextLine());
      

    If you have some experiences in C#, they expect you do to it with the 2nd method as well.