如何使用bufferedreader和treemap打印文本中最常出现的单词?- 浏览器

问题描述 投票:0回答:1

文本将只包含空格和单词。

输入示例。

thanks for the help \n
the car works now   \n
thanks              \n

输出:the -因为它的词性比 "谢谢 "小。

 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);
     }
 }

我的一次测试失败了,我真的不知道为什么这就是为什么我需要另一种方法。

java arrays string bufferedreader treemap
1个回答
0
投票

在你问题的标题中,你提到了TreeMap,但实际上你并没有使用它。

如果你把你实例化地图的那一行替换为

         NavigableMap < String, Integer > frequency = new TreeMap < > ();

然后,你可以用一个对地图的查询来替换for循环。

System.out.println(frequency.lastEntry().key)

你可以在这里阅读文档: https:/docs.oracle.comjavase8docsapijavautilTreeMap.html#lastEntry--。

© www.soinside.com 2019 - 2024. All rights reserved.