Tuesday, November 18, 2008

scanner class

Java 5 introduced Scanner class which has a functionality similar to the Reader in addition to the StringTokenizer class. Scanner can read input from a File, InputStream and ReadableByteChannel and can tokenize this data. It is more powerful than StringTokenizer, because it can parse primitives directly instead of taking them as String and parsing them to the corresponding primitive type.
Assume that we want to take the user input which consists of two Strings (e.g. name and last name) and an integer (e.g. student number).
Let's see how Scanner class works:
First we will link scanner to some input source.

// I link Scanner to System input.
Scanner scanner = new Scanner(System.in);

Then Scanner will take the input from user and parse the input values to desired variables.

String name = scanner.next();
String lastName = scanner.next();
int studentNumber = scanner.nextInt();
// above I parsed anything I needed, below I'll close my Scanner.
scanner.close();
/*Scanner closed. If the input source implements Closeable interface, it will be closed after that method call.*/


It is also possible to parse numbers with base other than decimal.

scanner.useRadix(2); // I'm setting Scanner to take a binary number as input
int number = scanner.nextInt();
// assume that the input was "101" which's "5" in decimal base
// then number is now "5".

No comments:

Post a Comment