设有一个含若干水果单词组成的字符串数组,编程统计该数组中共有多少种水果。假设调试的数据如下: String fruit[]= { "apple","pear","apple","apple","orange","pear","apple"};
时间: 2023-07-02 21:18:47 浏览: 73
可以使用哈希表来统计每种水果出现的次数,然后再统计哈希表中键值对的数量即可得到不同种类的水果数量。
以下是Java代码示例:
```java
import java.util.HashMap;
public class FruitCounter {
public static void main(String[] args) {
String fruit[] = {"apple", "pear", "apple", "apple", "orange", "pear", "apple"};
HashMap<String, Integer> fruitCount = new HashMap<String, Integer>();
for (int i = 0; i < fruit.length; i++) {
if (fruitCount.containsKey(fruit[i])) {
fruitCount.put(fruit[i], fruitCount.get(fruit[i]) + 1);
} else {
fruitCount.put(fruit[i], 1);
}
}
System.out.println("共有" + fruitCount.size() + "种水果:");
for (String fruitName : fruitCount.keySet()) {
System.out.println(fruitName + "出现了" + fruitCount.get(fruitName) + "次");
}
}
}
```
输出结果:
```
共有3种水果:
orange出现了1次
pear出现了2次
apple出现了4次
```
阅读全文