2

I am trying to receive input using java.util.Scanner:

Scanner scanner = new Scanner(System.in);
int bla = scanner.nextInt();
String blubb = scanner.nextLine();

But the nextLine() command just gets skipped and an empty string is returned. How can I solve this problem?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
CBenni
  • 555
  • 1
  • 7
  • 20

3 Answers3

11

The nextInt method does not consume the new line character after the integer so when you call nextLine it just reads the new line character immediately following the integer.

Example

If you have this input:

42\n
foo\n

The readInt call consumes the 42 but not the new line character:

\n
foo\n

Now when you call readLine it consumes the rest of the first line, which contains only the new line character.

Solution

Try discarding the rest of the line after the integer:

int bla = scanner.nextInt();
scanner.nextLine(); // Discard the rest of the line.
String blubb = scanner.nextLine();

Or use nextLine consistently to read each line and then parsing the string to an integer yourself:

String blaString = scanner.nextLine();
int bla = Integer.valueOf(blaString);
String blubb = scanner.nextLine();
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • +1 I prefer the second option myself, that way you can do some checking for incorrect input, instead of just waiting for the user to stumble into providing an `int` to the scanner. – NominSim Dec 21 '12 at 16:51
  • Thank you. Sorry for this dumb question >_ – CBenni Dec 21 '12 at 17:15
4

It isn't skipped:

int bla = scanner.nextInt(); 

Doesn't consume a new line, so your scanner is still on the first line when you hit Enter after you input your int. Then the scanner sees that it needs to consume the current line (The one where you inputted the int) and puts that remainder in blubb.

NominSim
  • 8,447
  • 3
  • 28
  • 38
-2

I have had similar issues when my scanner was static. I made a new scanner that was local and it didn't skip over input requests.

Zach
  • 51
  • 7