Bookmark and Share

Wednesday, July 8, 2009

Using Java's Scanner Class to Read Input

The Scanner class must be imported from java.util. It provides a wrapper class that encapsulates an input stream, such as stdin, and it provides a number of convenience methods for reading lines and then breaking a line into tokens. This set of notes will cover the set of Scanner methods that you will use most frequently. You can look at the Scanner's API to get the full list of methods that a Scanner provides.

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:

     Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

As another example, this code allows long types to be assigned from entries in a file myNumbers:

      Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

     String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

prints the following output:

     1
2
red
blue

The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

     String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i);
s.close();

More Magazines