Java Reference
In-Depth Information
9
public static final int
OCCURRENCES = 2000;
10
11
public static void
main(String[] args)
12
throws
FileNotFoundException {
13
System.out.println("This program displays the most");
14
System.out.println("frequently occurring words from");
15
System.out.println("the book Moby Dick.");
16
System.out.println();
17
18
// read the book into a map
19
Scanner in =
new
Scanner(
new
File("mobydick.txt"));
20
Map<String, Integer> wordCountMap = getCountMap(in);
21
22
for
(String word: wordCountMap.keySet()) {
23
int
count = wordCountMap.get(word);
24
if
(count > OCCURRENCES) {
25
System.out.println(word + " occurs " +
26
count + " times.");
27
}
28
}
29
}
30
31
// Reads book text and returns a map from words to counts.
32
public static
Map<String, Integer> getCountMap(Scanner in) {
33
Map<String, Integer> wordCountMap =
34
new
TreeMap<String, Integer>();
35
36
while
(in.hasNext()) {
37
String word = in.next().toLowerCase();
38
if
(wordCountMap.containsKey(word)) {
39
// never seen this word before
40
wordCountMap.put(word, 1);
41
}
else
{
42
// seen this word before; increment count
43
int
count = wordCountMap.get(word);
44
wordCountMap.put(word, count + 1);
45
}
46
}
47
48
return
wordCountMap;
49
}
50 }
Search WWH ::
Custom Search