Проблема с отображением слова, если у меня слишком много пустых строк - PullRequest
0 голосов
/ 18 февраля 2020

Я не хотел повторять другой вопрос, я решил проблему, в которой я публикую наиболее распространенное слово в тексте, но у меня есть проблема, она не работает, если у меня больше пустых строк, как я могу решить Это? Я пробовал другие способы 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();
        }
    }
}

}

1 Ответ

0 голосов
/ 18 февраля 2020

Измените свой for l oop, чтобы не добавлять в свой 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);
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...