Sunday 5 November 2017

java - 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.



itemprop="text">
class="normal">Answer




nextInt doesn't read
the following new-line character, so the first nextLine ( href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()"
rel="noreferrer">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 +
"<");

}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...