【发布时间】: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吗?
-
是的,从我的测试来看,如果我没有空行,它就会显示出来。