1

I've been writing this program to count the vowels in string/a line of strings. Now, I've got the whole program worked out and it does correctly output the number of vowels for all inputs, but the problem is that the first input of the array is always 0 / nonexistant for some reason.

I'll give you an example and the code here, it's kind of hard to explain:

Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt() //this would be the number of lines of strings
String[] array = new String[numberOfEntries];
int k = 0;
while(sc.hasNext() && k < numberOfEntries){
    array[k] = sc.nextLine();
    k++;
}

So this is the part of the code that is relevant to the problem, the rest of it is fine. For some reason, when I input the following lines:

5
abcd
efgh
ijkl
mnop
qrst

The output I will get if I outprint the array is this:

[, abcd, efgh, ijkl, mnop]

I've tried using just the

for(int i = 0; i < array.length; i++){
    array[i] = sc.nextLine();
}

thinking that it might solve the issue but nothing changed. I am out of ideas now, though I am sure I just made some silly little error somewhere and I just don't see it.

Kind regards, George

George Waat
  • 167
  • 2
  • 8
  • possible duplicate of [Scanner issue when using nextLine after nextXXX](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx) – Tom May 24 '15 at 11:20

3 Answers3

3

You get the empty line because of the '\n' that sits in the buffer after you call nextInt(). You press Enter after typing in your integer. Scanner consumes the integer in the call of nextInt(), but it does not touch '\n' that follows.

To fix this problem, call nextLine after reading your int, and discard the result:

int numberOfEntries = sc.nextInt();
sc.nextLine(); // Throw away the '\n' after the int
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

The statement int numberOfEntries = sc.nextInt(); reads the number, leaving the next character (a newline) as the next character to be read.

The first call to sc.nextLine() see this newline and recognizes it as the end on an (empty) line. For your sample input, this causes the call to return an empty string.

The solution is to add an extra call to sc.nextLine() after the sc.nextInt() to consume (and then discard) any characters after the last digit up to the end of the line.

(Actually ... this is a fairly common beginner's mistake with the Scanner API.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Thats because the Scanner.nextInt() method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine().

optional
  • 2,504
  • 4
  • 18
  • 30