Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

548 Part II: The Java Library


// 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;
}
}
}

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

In this version, the numbers written totest.txtare separated by commas and spaces. The
use of the delimiter pattern “, *” tellsScannerto match a comma and zero or more spaces as
delimiters. The output is the same as before.
You can obtain the current delimiter pattern by callingdelimiter( ), shown here:

Pattern delimiter( )

Other Scanner Features

Scannerdefines several other methods in addition to those already discussed. One that is
particularly useful in some circumstances isfindInLine( ). Its general forms are shown here:

String findInLine(Patternpattern)
String findInLine(Stringpattern)

This method searches for the specified pattern within the next line of text. If the pattern is
found, the matching token is consumed and returned. Otherwise, null is returned. It operates
independently of any delimiter set. This method is useful if you want to locate a specific
pattern. For example, the following program locates the Age field in the input string and
then displays the age:

// Demonstrate findInLine().
import java.util.*;

class FindInLineDemo {
public static void main(String args[]) {
String instr = "Name: Tom Age: 28 ID: 77";

Scanner conin = new Scanner(instr);

// Find and display age.
conin.findInLine("Age:"); // find Age

if(conin.hasNext())
Free download pdf