rulururu

post Java Scanner Class

February 29th, 2008

Filed under: Java — Kai @ 12:56 pm

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

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)