14

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.

Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122
Favolas
  • 6,341
  • 27
  • 67
  • 112

3 Answers3

43

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 + "<");
}
Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122
1

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

Actually it doesn't answer the question completely(why your code isn't working) but you may use following code.

int n = Integer.parseInt(readInput.readLine());
for(int i = 0; i < n; ++i) {
    String line = readInput().readLine();
    // use line here
}

As for me it's more readable and even may save your time in such rare cases when testcases are incorrect(with extra info at the end of file)

BTW, seems you take part in some programming competition. Make note, that Scanner may be quite slow to input a lot of data. you may consider using BufferedReader with possible StringTokenizer (not needed in this task)

RiaD
  • 42,649
  • 10
  • 67
  • 110