Java Scanner read input with delimiters

Introduction

Scanner can define where a token starts and ends based on a set of delimiters.

The default delimiters are the whitespace characters.

To change the delimiters, call the useDelimiter() method, shown here:

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

Here, pattern is a regular expression that specifies the delimiter set.


// Use Scanner to compute an average a list of 
// comma-separated values.  
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
  public static void main(String args[]) throws IOException {

    int count = 0;
    double sum = 0.0;

    // Write output to a file.
    FileWriter fout = new FileWriter("test.txt");

    // Now, store values in comma-separated list.
    fout.write("2, 3.4,    5,6, 7.4, 9.1, 10.5, done");
    fout.close();/*w  ww.j  ava 2  s. c o m*/

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);

    // Set delimiters to space and comma.
    src.useDelimiter(", *");

    // Read and sum numbers.
    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;
        }
      }
    }

    src.close();
    System.out.println("Average is " + sum / count);
  }
}



PreviousNext

Related