Reputation: 155
I was reading the API for Java because I had a question on the difference between .nextLine()
and .nextDouble()
. In the API, it says this for .nextLine()
:
"Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."
Easy enough...it skips the current line you are on and then returns the line you just skipped. But for .nextDouble()
, it says this:
"Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched."
So does this mean that .nextDouble()
does not skip to a new line and that it only reads until the end of the double and then stops at the end of the line? This would help me in understanding a program I'm working on now. Thanks guys and gals!
Upvotes: 4
Views: 24042
Reputation: 10093
It reads the next token (between 2 separating characters,white characters usually), not the next 4 bytes. It then transforms that token to a double if it can.
Ex: Bla bla bla 12231231.2121 bla bla.
The 4th token can be read using nextDouble(). It reads 13 chars and it transforms that string into a double if possible.
Upvotes: 5
Reputation: 728
nextDouble()
only reads the next 4 bytes from the input stream which make up the double and does not advance to the next line, whereas nextLine() does. Also i think you need to understand that a new line is designated by the string '\n', and obviously a number will not contain a linebreak, so 'nextDouble()' will not 'advance' to the next line.
EDIT: Razvan is right
Upvotes: 0