Home » Java » java – The problem with the word display if I have too many blank lines-Exceptionshub

java – The problem with the word display if I have too many blank lines-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I did not want to repeat the other question, I solved a problem in which I post the most common word in the text, but I have a problem, it does not work if I have more blank lines, how can I solve it?
I tried other ways of stackoverflow, but failed.
This is my code.

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

}

How to&Answers:

Modify your for loop so that you’re not adding to your map on a blank line.

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