javajava.util.scanner

Why is nextLine() returning an empty string?


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.


Solution

  • 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 + "<");
    }