Java设有一个含若干水果单词组成的字符串数组,String[] fruits = {"apple", "pear", "apple", "apple","orange","pear", "apple"};编程统计有多少种水果
时间: 2023-07-02 20:19:31 浏览: 40
可以使用一个 HashMap 来统计每种水果出现的次数,键为水果的名称,值为水果出现的次数。遍历整个水果数组,如果水果名称已经在 HashMap 中出现过,则将对应的值加1,否则将该水果名称加入 HashMap 中,并将值设为1。最后,HashMap 中键值对的数量即为不同水果的种类数。
以下是 Java 代码示例:
```java
import java.util.HashMap;
public class FruitCount {
public static void main(String[] args) {
String[] fruits = {"apple", "pear", "apple", "apple", "orange", "pear", "apple"};
HashMap<String, Integer> map = new HashMap<>();
for (String fruit : fruits) {
if (map.containsKey(fruit)) {
map.put(fruit, map.get(fruit) + 1);
} else {
map.put(fruit, 1);
}
}
System.out.println("不同水果的种类数为:" + map.size());
}
}
```
输出结果为:
```
不同水果的种类数为:3
```