文本将仅包含空格和单词。
示例输入:
thanks for the help \n
the car works now \n
thanks \n
输出: - 因为它的字典顺序比“Thanks”小。
public class Main {
public static void main(String[] args) throws IOException {
String line;
String[] words = new String[100];
Map < String, Integer > frequency = new HashMap < > ();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) {
words = line.split("\\W+");
for (String word: words) {
String processed = word.toLowerCase();
processed = processed.replace(",", "");
if (frequency.containsKey(processed)) {
frequency.put(processed,
frequency.get(processed) + 1);
} else {
frequency.put(processed, 1);
}
}
}
}
int mostFrequentlyUsed = 0;
String theWord = null;
for (String word: frequency.keySet()) {
Integer theVal = frequency.get(word);
if (theVal > mostFrequentlyUsed) {
mostFrequentlyUsed = theVal;
theWord = word;
} else if (theVal == mostFrequentlyUsed && word.length() <
theWord.length()) {
theWord = word;
mostFrequentlyUsed = theVal;
}
}
System.out.printf(theWord);
}
}
我的一项测试失败了,我真的不知道为什么这就是我需要另一种方法的原因。
最佳答案
在问题标题中您提到了 TreeMap,但实际上并没有使用它。
如果将实例化 map 的行替换为
NavigableMap < String, Integer > frequency = new TreeMap < > ();
然后您可以将 for 循环替换为对 map 的单个查询:
System.out.println(Frequency.lastEntry().key)
您可以在此处阅读文档:https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#lastEntry--
关于java - 如何使用 bufferedreader 和 treemap 打印文本中最常见的单词? - java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61961452/