Java: Summary - Scanner
The main use of java.util.Scanner is to read values from System.in or a file.
Many Scanner methods fit a simple pattern: nextXYZ()
scans and returns a value of type XYZ. hasNextXYZ()
returns true if something of type XYZ is available to be read next.
Additional types. The summary below just shows methods for ints and doubles because these are most common, but Scanner also supports BigDecimal, BigInteger, Float (returns float), Boolean (returns boolean), Long (returns long), Short (returns short), and Byte (returns byte). The XYZ in the prototypes below stands of for one of these additional types.
Scanner methods
Assume: int i, double d, String s, boolean b, Scanner sc, and x stands for a type that should be clear from context.
Constructors | ||
sc = | new Scanner(System.in); | Creates a Scanner which reads from System.in. |
sc = | new Scanner(s); | Creates a Scanner which reads from String s. |
Most common "next" input methods. | ||
s = | sc.next() | Returns next "token", which is more or less a "word". |
s = | sc.nextLine() | Returns an entire input line as a String. |
i = | sc.nextInt() | Returns next integer value. |
d = | sc.nextDouble() | Returns next double value. |
x = | sc.nextXYZ() | Returns value of type XYZ (primitive value if possible), where XYZ is one of BigDecimal, BigInteger, Boolean, Byte, Float, or Short. |
Methods that test for availability of legal input for loops, optional elements, error checking. | ||
b = | sc.hasNext() | True if another token is available to be read. |
b = | sc.hasNextLine() | True if another line is available to be read. |
b = | sc.hasNextInt() | True if another int is available to be read. |
b = | sc.hasNextDouble() | True if another double is available to be read. |
b = | sc.hasNextXYZ() | XYZ stands for one of the input types available above. |
Numerical input methods other than decimal | ||
x = | sc.nextXYZ(radix) | Returns next value where XYZ is one of Int, Long, Short, Byte, or BigInteger. Converts the input from base/radix specified in the parameter. |
Other | ||
sc.close() | Closes the input stream. Many programs omit this if they are reading from the console, but it's a good habit to always close a Scanner when you're finished with all reading. Scanner is often used for file input. Even when you think you're reading the console, System.in may have been redirected to come from a file. Close the Scanner object so that the file is no longer locked for reading. This is even more important if you are reading many files, because each open file uses system resources, and closing the Scanner will release those resources. |
And much more
Scanner has a lot of other features, with support for regular expressions, delimiter definitions, skipping input, locales, searching in a line, reading from inputs including String, ...