This problem maybe related to how the Scanner
works.
See documentation of next
:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
and of nextLine
:
Advances this scanner past the current line and returns the input that was skipped.
The default delimiter includes the newline character (\n
).
I assume the input has a leading newline (empty line) that is being removed by next
but not by nextLine
.
Test:
new Scanner("\ntest\n").next()
returns "test"
new Scanner("\ntest\n").nextLine()
returns ""
(empty string)
This will happen, for example, if the previous Scanner
input was read with nextInt()
(or similar) - this does not consume any newline after the number:
var sc = new Scanner("123\n456\n");
var i = sc.nextInt(); // will be 123
var str = sc.nextLine(); // will be the empty string "" (between 123 and \n)
str = sc.nextLine(); // now it is "test"
String
used as input for the Scanner
since it is easier to describe, same will happen with user input where a newline will be read if user types the return key (usually to end input)
If this is the case, solution is to call nextLine()
after reading a number (or even read the number with nextLine()
and then parsing it).
For more details, please check this question: Scanner is skipping nextLine() after using next() or nextFoo()?
this answer is based on the comment that the Exception mentions the empty string ""
as unparseable
also consider vsfDawg's answer - next()
will stop at whitespace character