-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path$5_CountingWords.java
More file actions
50 lines (41 loc) · 1.36 KB
/
$5_CountingWords.java
File metadata and controls
50 lines (41 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package src;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class $5_CountingWords {
public static void main(String[] args) {
String filePath = "src/$5_CountingWords.txt";
Map<String, Integer> wordCount_Map = new HashMap<>();
String mostFrequentWord = null;
int maxWordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] multipleWords = line.split("\\s+");
for (String singleWord : multipleWords) {
if (wordCount_Map.containsKey(singleWord)) {
int count = wordCount_Map.get(singleWord);
wordCount_Map.put(singleWord, count + 1);
} else {
wordCount_Map.put(singleWord, 1);
}
// Update most used word
if (wordCount_Map.get(singleWord) > maxWordCount) {
mostFrequentWord = singleWord;
maxWordCount = wordCount_Map.get(singleWord);
}
}
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
System.out.println("Word count overview:");
for (String word : wordCount_Map.keySet()) {
int count = wordCount_Map.get(word);
System.out.println(word + ": " + "Count:" + " " + count);
}
System.out.println("Most used word: " + mostFrequentWord + " (" + maxWordCount + " times)");
}
}