Java Reference
In-Depth Information
Normally, Scanner uses whitespace to delimit the tokens read using next() . However, we can change that and specify
whatever characters we want to be used as delimiters. For example, to use a colon as a delimiter, we can write this:
in.useDelimiter(":");
When we use in.next() in our program, it will return a string consisting of the characters up to, but not
including, the next colon. To use a colon or a comma, say, as a delimiter, we can write this:
in.useDelimiter("[:,]"); //make a set using [ and ]
The square brackets denote a set. To use a colon, comma, period, or question mark, we write this:
in.useDelimiter("[:,\\.\\?]");
The period and question mark are so-called meta characters (used for a special purpose), so we must specify
each using an escape sequence: \. and \?. Recall that, within a string, \ is specified by \\.
If we want to specify that a delimiter is any character that is not a lowercase letter, we write this:
in.useDelimiter("[^a-z]"); // ^ denotes negation, "not"
The expression a-z denotes a range—from a to z .
If we add + after the right square bracket, it denotes a sequence of “one or more” nonlowercase characters. So, since
we want that a delimiter to be a sequence of “one or more” nonletters (neither uppercase nor lowercase), we write this:
in.useDelimiter("[^a-zA-Z]+");
We now write Program P8.2 to do the frequency count of words in the file wordFreq.in . It simply reflects the
algorithm we outlined previously.
Program P8.2
import java.io.*;
import java.util.*;
public class WordFrequencyBST {
static Scanner in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new Scanner(new FileReader("wordFreq.in"));
out = new PrintWriter(new FileWriter("wordFreq.out"));
BinaryTree bst = new BinaryTree();
in.useDelimiter("[^a-zA-Z]+");
while (in.hasNext()) {
String word = in.next().toLowerCase();
TreeNode node = bst.findOrInsert(new NodeData(word));
node.data.incrFreq();
}
out.printf("\nWords Frequency\n\n");
bst.inOrder();
in.close(); out.close();
} // end main
} //end class WordFrequencyBST
Search WWH ::




Custom Search