Java Reference
In-Depth Information
At this point, the input cursor is positioned at the newline character at the end of
the first line of input. The fourth call on nextDouble skips past this newline charac-
ter and consumes the text “2.8”:
308.2 14.9 7.4\n2.8\n\n\n3.9 4.7 -15.4\n2.8\n
input
cursor
Notice that when it skipped past the first newline character, the input cursor moved
into data stored on the second line of input. At this point, the input cursor is positioned
at the end of the second line of input, because it has consumed the “2.8” token. When a
fifth call is made on nextDouble , the Scanner finds three newline characters in a row.
This isn't a problem for the Scanner , because it simply skips past any leading white-
space characters (spaces, tabs, newline characters) until it finds an actual token. So, it
skips all three of these newline characters and consumes the text “3.9”:
308.2 14.9 7.4\n2.8\n\n\n3.9 4.7 -15.4\n2.8\n
input
cursor
At this point the input cursor is positioned in the middle of the fifth line of input.
(The third and fourth lines were blank). The program continues reading in this manner,
consuming the remaining three numbers in the input file. After it reads the final token,
“2.8”, the input cursor is positioned at the newline character at the end of the file:
308.2 14.9 7.4\n2.8\n\n\n3.9 4.7 -15.4\n2.8\n
input
cursor
If you attempted to call nextDouble again, it would throw a
NoSuchElementException because there are no more tokens left to process. But
remember that the ShowSum2 program has a while loop that calls hasNextDouble
before it calls nextDouble . When you call methods like hasNextDouble ,the
Scanner looks ahead in the file to see whether there is a next token and whether it is
of the specified type (in this case, a double ). So, the ShowSum2 program will
continue executing until it reaches the end of the file or until it encounters a token
that cannot be interpreted as a double .
When the input cursor reaches the newline at the end of the file, the Scanner
notices that there are no more double values to read and returns false when
hasNextDouble is called. That return stops the while loop from executing and
causes the program to exit.
 
 
Search WWH ::




Custom Search