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
- Scanner: useDelimiter(String pattern)
- Scanner: useDelimiter(Pattern pattern)
- 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