Friday 12 July 2019

java - Trouble with order of reading next line with Scanner

The difference in execution, with change in orders, is due to the fact that new-line is not consumed by nextInt(), nextDouble(), next() or nextFoo() methods.



Therefore, whenever you place a call to nextLine() after any of those methods, it consumes that newline, and virtually skips over that statement.




The fix is simple, don't use nextFoo() methods before nextLine(). Try :-



i2 = Integer.parseInt(scan.nextLine());
d2 = Double.parseDouble(scan.nextLine());
s2 = scan.nextLine();


Or else, you could consume the new-line by



i2 = scan.nextInt();

d2 = scan.nextDouble();
scan.nextLine(); //---> Add this before the nextLine() call
s2 = scan.nextLine();


Order#3 works fine, as nextLine() is the first statement, and therefore, there are no left-over characters to consume.



Related: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

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