Scanner for tokenized input
Reading and tokenizing input with Scanner: hasNext checks, delimiters, and parsing event files.
Reading input with Scanner
java.util.Scanner breaks an input source into tokens (by default split on whitespace) and parses each token on demand. The source can be System.in, a String, or a File:
Scanner sc = new Scanner("42 3.14 hello");
int i = sc.nextInt(); // 42
double d = sc.nextDouble(); // 3.14
String w = sc.next(); // "hello"
Each next* call returns the next token and advances. nextInt/nextDouble parse the token to that type and throw InputMismatchException if it does not fit.
Guarding with hasNext*
To read until input runs out, test before you take. hasNext() / hasNextInt() / hasNextLine() return false at end of input (and hasNextInt returns false if the next token is not an integer), so the canonical loop is:
while (sc.hasNextLine()) {
String line = sc.nextLine();
// process line
}
next() reads a single whitespace-delimited token; nextLine() reads the rest of the current line (including the remaining text) and consumes the line terminator.
Custom delimiters
useDelimiter(regex) changes what separates tokens — the argument is a regular expression, tying directly back to Lesson 4.3. To split a CSV-style event line on commas:
Scanner sc = new Scanner("Event=LightOn,time=2000");
sc.useDelimiter(",");
String first = sc.next(); // "Event=LightOn"
String second = sc.next(); // "time=2000"
Worked example — reading an event file
The Greenhouse project reads an examples1.txt of one event per line. The robust shape opens a Scanner over the File, loops with hasNextLine, skips blanks, and closes the scanner when done:
try (Scanner sc = new Scanner(new File("examples1.txt"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.isEmpty()) continue;
parseEvent(line); // hand off to the regex parser from 4.3
}
}
Wrapping the Scanner in try-with-resources guarantees close() runs (releasing the file handle) even if parseEvent throws — the cleanup discipline from Module 3.