Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 18: java.util Part 2: More Utility Classes 547


int: 10
double: 12.2
String: one
boolean: true
String: two
boolean: false

When reading mixed data types, as the preceding program does, you need to be a bit
careful about the order in which you call thenextmethods. For example, if the loop reversed
the order of the calls tonextInt( )andnextDouble( ), both numeric values would have been
read asdoubles, becausenextDouble( )matches any numeric string that can be represented
as adouble.


Setting Delimiters

Scannerdefines where a token starts and ends based on a set ofdelimiters.The default delimiters
are the whitespace characters, and this is the delimiter set that the preceding examples have
used. However, it is possible to change the delimiters by calling theuseDelimiter( )method,
shown here:


Scanner useDelimiter(Stringpattern)

Scanner useDelimiter(Patternpattern)

Here,patternis a regular expression that specifies the delimiter set.
Here is the program that reworks the average program shown earlier so that it reads a
list of numbers that are separated by commas, and any number of spaces:


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


class SetDelimiters {
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();

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

Scanner src = new Scanner(fin);

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