【问题标题】:The problem with the word display if I have too many blank lines如果我有太多空行,单词显示的问题
【发布时间】:2020-02-18 17:39:55
【问题描述】:

我不想重复另一个问题,我解决了一个问题,我在文本中发布了最常用的单词,但是我有一个问题,如果我有更多的空行,它不起作用,我该如何解决它? 我尝试了其他的stackoverflow方法,但失败了。 这是我的代码。

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
    Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
        String currentLine = reader.readLine();
        while (currentLine != null) {
            String[] input = currentLine.replaceAll("[^a-zA-Z-\"\\n\\n\", \"\\n\"]", " ").toLowerCase().split(" ");
            for (int i = 0; i < input.length; i++) {
                if (map.containsKey(input[i])) {
                    int count = map.get(input[i]);
                    map.put(input[i], count + 1);

                } else {
                    map.put(input[i], 1);
                }
            }
            currentLine = reader.readLine();
        }
        String mostRepeatedWord = null;
        int count = 0;
        for (Map.Entry < String, Integer > m: map.entrySet()) {
            if (m.getValue() > count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
            } else if (m.getValue() == count) {
                String key = m.getKey();
                if (key.compareTo(mostRepeatedWord) < 0) {
                    mostRepeatedWord = key;
                }
            }
        }
        System.out.println(mostRepeatedWord);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

【问题讨论】:

  • 它不起作用?或者它是否将空行视为重复次数最多的单词?既然如此,修剪()这个词并忽略空字符串。
  • 如果我的文本中有很多白线,则不会显示任何内容。
  • 是的,因此可以假设它将白线视为一个单词并显示nothing吗?
  • 是的,从我的测试来看,如果我没有空行,它就会显示出来。

标签: java string hashmap


【解决方案1】:

修改您的 for 循环,这样您就不会在空白行中添加到您的 map

for (int i = 0; i < input.length; i++) {
  // Skip the blank lines
  if (!input[i].trim().equals("")) {

    if (map.containsKey(input[i])) {
      int count = map.get(input[i]);
      map.put(input[i], count + 1);
    } else {
      map.put(input[i], 1);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-22
    • 2011-02-14
    • 1970-01-01
    • 2023-03-14
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多