Untitled
unknown
java
2 years ago
1.6 kB
10
Indexable
import java.io.*;
import java.util.*;
public class WordFrequency {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
try {
FileReader reader = new FileReader("Datei1.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String word : line.split(" ")) {
words.add(word);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
// Sortieren der Wörter
Collections.sort(words);
// Erstellung der Worthäufigkeitsliste mit sortierten Wörtern
Map<String, Integer> wordFrequency = new HashMap<>();
String currentWord = words.get(0);
int currentCount = 1;
for (int i = 1; i < words.size(); i++) {
if (words.get(i).equals(currentWord)) {
currentCount++;
} else {
wordFrequency.put(currentWord, currentCount);
currentWord = words.get(i);
currentCount = 1;
}
}
wordFrequency.put(currentWord, currentCount);
// Ausgabe der Worthäufigkeitsliste
for (String word : wordFrequency.keySet()) {
int frequency = wordFrequency.get(word);
System.out.println(word + " kommt " + frequency + " Mal vor.");
}
}
}
Editor is loading...