Java Scanner Class
February 29th, 2008
Today I’d like to introduce to you the Scanner Class which can be used in Java 1.5 and later.
It is a very useful new class that can parse text for primitive types and substrings using regular expressions. Before arguing round and round the subject I’m gonna give you an example:
import java.util.Scanner; import java.io.*; public class Test { public static void main(String[] args) { int n; double d; String foo; System.out.print("Enter an integer, a floating-point number, and a word: "); String line = Console.In.ReadLine(); Scanner in = new Scanner(line); n = in.nextInt(); d = in.nextDouble(); foo = in.next(); System.out.println("integer: " + n + ", float: " + d + ", word: " + word); } }
For each of the primitive types there is a corresponding nextXxx() method that returns a value of that type. If the string cannot be interpreted as that type, then an InputMismatchException is thrown.
There are a number of other useful methods in the Scanner class such as skip() to jump over input, useDelimiter() defines a delimiter in place of the default white space, and findInLine() to search for substrings.
You can also give an input direcly to the scanner:
//from the keyboard: Scanner keyboardScan = new Scanner(System.in); //from a file: Scanner fileScan = new Scanner(new FileReader("file.txt");
A common way, from a stream, can be done very short:
int n = new Scanner( getResourceAsStream("file.txt") ).nextInt();
For detecting EOF (End of File) this is important (methods return boolean):
fileScan.hasNext(); fileScan.hasNextLine();
When with floading point numbers you’d note that for example in Germany floading point numbers are written with comma instead of dot.
Scanner scanner = new Scanner( "1,3" ); double d = scanner.nextDouble();
Won’t detect that “1,3″ is a double and return an java.util.InputMismatchException, the reason why is very logical:
The default Locale-Object for the Scanner is what Locale.getDefault() returns - on an English computer it will return Locale.English or something similar. If you like to set it to another language you can simply to that as follows:
Scanner scanner = new Scanner( "1,3" ).useLocale( Locale.GERMAN );
A detailed overview can be found in J2se 1.5 docs: Class Scanner



I’m not as surprised about that as you might think ’cause there a several problems in software development you can just solve that way or you chose kinda “dirty” way. Even thougth the book is exhausting to read ’cause it’s not written the way most book for programmers are - it’s really abstract which means they’re almost never writing about problems that occur the development of a software product but all-time about compareable situations in real life. None the less I can without any doubt recommend it to you as a book every programmer should have read once or maybe twice.


