Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is nextLine() returning an empty string? [duplicate]

Tags:

java

This is probably one of the easiest things but I'm not seeing what I'm doing wrong.

My input consist of one first line with a number (the number of lines to read), a bunch of lines with data and a final line only with \n. I should process this input and after the last line, do some work.

I have this input:

5
test1
test2
test3
test4
test5
      /*this is a \n*/

And for reading the input I have this code.

int numberRegisters;
String line;

Scanner readInput = new Scanner(System.in);

numberRegisters = readInput.nextInt();

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}

My question is why I'm not printing anything? Program reads the first line and then does nothing.

like image 696
Favolas Avatar asked Apr 16 '13 15:04

Favolas


2 Answers

nextInt doesn't read the following new-line character, so the first nextLine (which returns the rest of the current line) will always return an empty string.

This should work:

numberRegisters = readInput.nextInt();
readInput.nextLine();
while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}

But my advice is not to mix nextLine with nextInt / nextDouble / next / etc. because anyone trying to maintain the code (yourself included) may not be aware of, or have forgotten, the above, so may be somewhat confused by the above code.

So I suggest:

numberRegisters = Integer.parseInt(readInput.nextLine());

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}
like image 110
Bernhard Barker Avatar answered Oct 01 '22 23:10

Bernhard Barker


I think I've see this issue before. I think you need to add another readInput.nextLine() or else you're just reading between the end of the 5, and the \n after that

int numberRegisters;
String line;

Scanner readInput = new Scanner(System.in);

numberRegisters = readInput.nextInt();
readInput.nextLine();

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}
like image 32
Sam I am says Reinstate Monica Avatar answered Oct 01 '22 23:10

Sam I am says Reinstate Monica