Java Reference
In-Depth Information
and added to the sum. Otherwise, the value is read (as a String ) with
next and ignored. The hasNext and next methods should be familiar to
youthey are two of the methods of Iterator . And indeed Scanner imple-
ments Iterator<String> so you can easily iterate through the tokens in
an input source. [3] The remove method of Scanner tHRows UnSupportedOper-
ationException .
[3] Note that Scanner is an Iterator not an Iterable , so it can not be used with the enhanced for loop.
This limitation may be removed in the future.
The hasNext method returns TRue if the scanner has another token to re-
turn from next . For each primitive type except char , hasNext Type asks if
the next token is of that type, and if so, next Type will return it. For the
integer types there are overloads of hasNext Type and next Type that take
an int radix for the number. For example, hasNextInt(8) will return TRue
if the next token is a valid octal representation of an int value. The de-
fault radix of the scanner (initially 10) can be changed with the useRadix
method, and retrieved from the radix method.
The hasNext method also has two additional overloads that take a pattern
and will return true only if the next token matches the given pattern.
Similarly, next also has two overloads that take a pattern describing the
token to return.
All the methods that get the next token operate as follows: Delimiters
from the current position to the first non-delimiter are ignored; then
the next delimiter is found; if the input between the delimiters matches
the pattern then a token has been found and the current position is ad-
vanced to the first character after the token. If there is no next token
then NoSuchElementException is thrown. If the method requires a specific
type of token or a token that matches a given radix or pattern, and the
next token does not meet those criteria, then InputMismatchException is
thrown. If an exception is thrown then the position of the scanner is un-
changed.
Input sources for scanners can come from several places. There is
a constructor that takes a Readable character source, one that takes
a String , and several that take byte sources: File , InputStream or
 
 
Search WWH ::




Custom Search