我有一个已经面对了两天的问题。给了我一个文本,该文本跨越多行,并且我必须显示文本中最常见的单词,但是例如,常见的单词换句话说出现相同的次数,以显示词典序的最小值。这是我的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
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]", " ").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();
}
}
System.out.println(mostRepeatedWord);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我的问题是,如何找到词典序的最小值?
Java中的比较起初遵循一个有点棘手的标准-字典比较也不例外,但是一旦您了解了它的发展过程,便有了对它的支持,这使得它变得非常容易。
我建议您在for循环的末尾,如果计数相等,则将当前字与mostRepeatedWord
进行比较,如果它较小(前接),则将其存储到mostRepeatedWord
中。对于字典比较,请使用m.getKey().compareTo(mostRepeatedWord)
(如果要忽略比较中的大写和小写字母,请使用m.getKey().compareToIgnoreCase(mostRepeatedWord)
)。如果m.getKey()
在字典上排在mostRepeatedWord
之前(小于它),则该方法将返回一个负数(严格小于0的任何数字,未指定哪个数字)。
以这种方式,在循环mostRepeatedWord
之后,按字典顺序保存出现频率最高的单词(在地图中具有最高的计数)。
并且如果您想知道我是否愿意为您编写代码,不,您自己做将会学到很多。如果您遇到麻烦,请在评论中进行跟进,不过,我会回复。
compareTo
方法的文档说:
返回:
如果参数字符串等于此字符串,则为值0;一个值如果此字符串在字典上小于该字符串,则小于0论点如果此字符串是在字典上大于字符串参数。
String.compareTo()
String.compareTo()
Comparable
interface的约定,因为此对象小于,等于或大于指定的对象,因此返回负整数,零或正整数。