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.
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 next integer value. |
| 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, BigIn |