用JAVA实现:从键盘读入N个英文单词,设计程序统计每个英文单词出现的次数。要求其基本功能是:(1) 从键盘读入N的值,构建用于存储英文单词的字符串数组;(2)从键盘读入N个英文单词存入数 组或数组列表中,并将所有英文单词输出;i(3)统计每个英文单词出现的次数,并将统计结果 输出。
时间: 2024-03-01 21:50:54 浏览: 88
好的,我可以帮你解答这个问题。首先,我们可以使用Java的Scanner类来从键盘读入N的值,然后构建一个用于存储英文单词的字符串数组。代码如下:
```java
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入单词个数N:");
int n = scanner.nextInt();
String[] words = new String[n];
System.out.println("请输入" + n + "个单词:");
for (int i = 0; i < n; i++) {
words[i] = scanner.next();
}
System.out.println("输入的单词为:");
for (String word : words) {
System.out.print(word + " ");
}
System.out.println();
// 统计单词出现次数
// ...
}
}
```
接下来,我们需要统计每个英文单词出现的次数。我们可以使用Java的HashMap来实现,键为单词,值为出现次数。代码如下:
```java
import java.util.HashMap;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入单词个数N:");
int n = scanner.nextInt();
String[] words = new String[n];
System.out.println("请输入" + n + "个单词:");
for (int i = 0; i < n; i++) {
words[i] = scanner.next();
}
System.out.println("输入的单词为:");
for (String word : words) {
System.out.print(word + " ");
}
System.out.println();
// 统计单词出现次数
HashMap<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
if (wordCount.containsKey(word)) {
int count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1);
}
}
System.out.println("单词出现次数为:");
for (String word : wordCount.keySet()) {
int count = wordCount.get(word);
System.out.println(word + ": " + count);
}
}
}
```
这样,我们就可以从键盘读入N个英文单词,并统计每个英文单词出现的次数了。
阅读全文