从控制台输入一句英语,统计个单词出现的次数,使用hashmap完成
时间: 2024-03-21 12:38:53 浏览: 189
可以按照以下步骤实现:
1. 从控制台读取一句英语,可以使用Scanner类实现。示例代码如下:
```java
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一句英语:");
String sentence = scanner.nextLine();
```
2. 将句子按空格分割成单词,可以使用String的split()方法实现。示例代码如下:
```java
String[] words = sentence.split(" ");
```
3. 创建一个空的HashMap对象,用于存储单词出现的次数。示例代码如下:
```java
Map<String, Integer> wordCount = new HashMap<String, Integer>();
```
4. 遍历单词数组,统计每个单词出现的次数,并存储到HashMap中。示例代码如下:
```java
for (String word : words) {
if (wordCount.containsKey(word)) {
// 如果单词已经在Map中出现过,则将出现次数加1
int count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
// 如果单词还没有在Map中出现过,则将出现次数设置为1
wordCount.put(word, 1);
}
}
```
5. 遍历HashMap,输出每个单词出现的次数。示例代码如下:
```java
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
System.out.println(word + ": " + count);
}
```
完整代码如下:
```java
import java.util.*;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一句英语:");
String sentence = scanner.nextLine();
String[] words = sentence.split(" ");
Map<String, Integer> wordCount = new HashMap<String, Integer>();
for (String word : words) {
if (wordCount.containsKey(word)) {
int count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
System.out.println(word + ": " + count);
}
}
}
```
运行程序,输入一句英语,即可输出每个单词出现的次数。
阅读全文