Setting Delimiters for Scanner : Scanner « File « Java Tutorial






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

The default delimiters are the whitespace characters.

To Change the delimiters

  1. Scanner: useDelimiter(String pattern)
  2. Scanner: useDelimiter(Pattern pattern)
  3. Pattern is a regular expression that specifies the delimiter set.

Use Scanner to compute the average of a list of comma-separated values.

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 {

    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);
    // Set delimiters to space and comma.
    // ", *" tells Scanner to match a comma and zero or more spaces as
    // delimiters.

    src.useDelimiter(", *");

    // Read and sum numbers.
    while (src.hasNext()) {
      if (src.hasNextDouble()) {
        System.out.println(src.nextDouble());
      } else {
        break;
      }
    }
    fin.close();
  }
}
2.0
3.4
5.0
6.0
7.4
9.1
10.5








11.54.Scanner
11.54.1.Using Scanner to receive user input
11.54.2.Using Scanner: the complement of Formatter
11.54.3.In general, to use Scanner, follow this procedure
11.54.4.Creating a Scanner: read from standard input: Scanner conin = new Scanner(System.in)
11.54.5.Creating a Scanner to read from a string
11.54.6.Using Scanner to read several different unknown types of data
11.54.7.Setting Delimiters for Scanner
11.54.8.To obtain the current delimiter pattern: Pattern delimiter( )
11.54.9.Searching for the specified pattern within the next line of text
11.54.10.To find within the next count characters