用java定义一个名为 WordCounter 的类,该类具有以下两个方法: void addWords(String text):将指定文本中的单词添加到此对象中。假设单词用空格分隔。 Map<String, Integer> getWordCounts():返回包含每个单词及其出现次数的映射。 然后,请编写一个程序,使用 WordCounter 类来计算给定文本中每个单词的出现次数,并按出现次数从高到低排序打印结果。要求忽略单词大小写,且在输出中不包括标点符号和数字。 例如,对于下面的输入文本: This is a test. That is also a test. Is this not a test? 应输出: a: 3 is: 3 test: 3 this: 2 that: 1 also: 1 not: 1 其中,每个单词按出现次数从高到低排序,如果出现次数相同,则按字母顺序排序
时间: 2024-03-10 19:45:15 浏览: 25
好的,下面是实现WordCounter类的Java代码:
```java
import java.util.*;
public class WordCounter {
private Map<String, Integer> wordCounts;
public WordCounter() {
wordCounts = new HashMap<>();
}
public void addWords(String text) {
String[] words = text.toLowerCase().replaceAll("[^a-zA-Z ]", "").split("\\s+");
for (String word : words) {
int count = wordCounts.getOrDefault(word, 0);
wordCounts.put(word, count + 1);
}
}
public Map<String, Integer> getWordCounts() {
return wordCounts;
}
}
```
然后是实现程序的代码:
```java
public class Main {
public static void main(String[] args) {
String inputText = "This is a test. That is also a test. Is this not a test?";
WordCounter wordCounter = new WordCounter();
wordCounter.addWords(inputText);
List<Map.Entry<String, Integer>> wordCountList = new ArrayList<>(wordCounter.getWordCounts().entrySet());
wordCountList.sort((o1, o2) -> {
int countCompare = o2.getValue().compareTo(o1.getValue());
if (countCompare == 0) {
return o1.getKey().compareTo(o2.getKey());
} else {
return countCompare;
}
});
for (Map.Entry<String, Integer> entry : wordCountList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
这个程序将输出以下内容:
```
a: 3
is: 3
test: 3
this: 2
also: 1
not: 1
that: 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)