Setting Delimiters

Scanner defines where a token starts and ends based on a set of delimiters. The default delimiters are the whitespace characters. It is possible to change the delimiters by calling the useDelimiter( ) method


Scanner useDelimiter(String pattern) 
Scanner useDelimiter(Pattern pattern)

pattern is a regular expression that specifies the delimiter set.


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class MainClass {
  public static void main(String args[]) throws IOException {
    int count = 0; 
    double sum = 0.0; 
 
    FileWriter fout = new FileWriter("test.txt"); 
 
    fout.write("2, 3.4,    5,6, 7.4, 9.1, 10.5, done"); 
    fout.close(); 
 
    FileReader fin = new FileReader("Test.txt"); 
 
    Scanner src = new Scanner(fin); 
 
    src.useDelimiter(", *"); 
 
    while(src.hasNext()) { 
      if(src.hasNextDouble()) { 
        sum += src.nextDouble(); 
        count++; 
      } 
      else { 
        String str = src.next();  
        if(str.equals("done")) break; 
        else { 
          System.out.println("File format error."); 
          return; 
        } 
      } 
    } 
 
    fin.close(); 
    System.out.println("Average is " + sum / count); 
  }
}
Home 
  Java Book 
    Essential Classes  

Scanner:
  1. Scanner
  2. Setting Delimiters
  3. findInLine( )
  4. findWithinHorizon( )
  5. skip( )
  6. new Scanner(FileReader file)
  7. new Scanner(InputStream source)
  8. Scanner: hasNext()
  9. Scanner: hasNextBoolean()
  10. Scanner: hasNextDouble()
  11. Scanner: hasNextInt()
  12. Scanner: hasNextLine()
  13. Scanner: next()
  14. Scanner: nextBoolean()
  15. Scanner: nextDouble()
  16. Scanner: nextInt()
  17. Scanner: nextLine()