0

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?

Bram
  • 2,515
  • 6
  • 36
  • 58
German Mumma
  • 21
  • 1
  • 5

2 Answers2

1

Insert input.nextLine() after your first nextInt() call. nextInt() will leave behind the newline character.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

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.

user3437460
  • 17,253
  • 15
  • 58
  • 106