我有一个问题已经困扰我两天了。 给我一个文本,该文本跨越几行,我必须显示文本中最常见的单词,但例如常见单词出现的次数相同,换句话说,以显示字典最小值。 这是我的代码:
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 中的比较遵循一个标准,一开始有点棘手 - 字典比较也不异常(exception),但是一旦您了解了它是如何进行的,就会有对它的支持,这使得它变得非常容易。
我建议在最后的 for 循环中,如果计数相等,则将当前单词与 mostRepeatedWord
进行比较,如果它较小(位于之前),则将其存储到 mostRepeatedWord
。对于字典比较,请使用 m.getKey().compareTo(mostRepeatedWord)
(或 m.getKey().compareToIgnoreCase(mostRepeatedWord)
如果您想忽略大写和大写之间的差异比较中小写)。如果 m.getKey()
按字典顺序位于 mostRepeatedWord
之前(小于它),该方法将返回一个负数(任何严格小于 0 的数字,未指定哪个数字) .
这样,在循环之后,mostRepeatedWord
将保留按字典顺序出现最频繁的单词(在 map 中计数最高)中最小的单词。
如果您想知道我是否会为您编写代码,不,您自己这样做会学到更多东西。如果您遇到麻烦,请在评论中跟进,我会回复。
compareTo 方法的文档说:
Returns:
the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
链接
- Documentation of
String.compareTo()
- Java String compareTo() Method with examples
- Documentation of the
Comparable
interface指定compareTo()
的约定,当该对象小于、等于或大于指定对象时返回负整数、零或正整数。
关于java - 显示文本中最常见的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60239384/