计算每个单词出现的个数 java
时间: 2024-05-15 07:15:54 浏览: 20
以下是Java代码,可以用来计算每个单词出现的次数:
```java
import java.util.HashMap;
public class WordCount {
public static void main(String[] args) {
String input = "Welcome to the jungle welcome to the jungle";
String[] words = input.split(" ");
HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
for (String word : wordCount.keySet()) {
System.out.println(word + " appears " + wordCount.get(word) + " times");
}
}
}
```
这个程序将输入字符串分割成单词数组,然后使用HashMap来存储每个单词出现的次数。在遍历单词数组时,每当遇到一个新单词时,就将其添加到HashMap中,并将其计数器初始化为1;如果遇到一个已经在HashMap中存在的单词,则将其计数器加1。最后,程序遍历HashMap并输出每个单词出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)