3

I'm experiencing an anomaly in java that i can't wrap my head around.

In my main class i have the following code:

(import java.util.*;)
...

Scanner input = new Scanner(System.in);

String name;
int i = 1;

System.out.println("How many names do you want to enter?");
int iteratorCount = input.nextInt();
iteratorCount++;

  while (i < iteratorCount){
  System.out.println("Ener name number "+i);
  name = input.nextLine();
  System.out.println(name);
  i++;
  }

But during the first itiration of the while loop i don't get asked to write a name. The text "Enter name number 1" does appear however. This is the output:

How many names do you want to enter?
>>5
Ener name number 1

Ener name number 2
>>Jack
Jack
Ener name number 3
>>John
John
Ener name number 4
>>Lisa
Lisa
Ener name number 5
>>Paul
Paul

where >> is user entered text.

Can anyone explain why this is happening?

Jack Pettersson
  • 1,400
  • 2
  • 13
  • 24

1 Answers1

6

Scanner#nextInt doesn't consume the '\n' character (the enter key you hit after you insert an int), scenario:

>>> How many names do you want to enter?
>>> 5 (and hit enter)
>>> Enter name number 
>>> \n (consumed)
>>> 

Solutions:

  • put another nextLine right after nextInt in order to consume that character instead
  • (not recommended but might help you to understand your problem) have another Scanner instance
Maroun
  • 87,488
  • 26
  • 172
  • 226