Java设有一个含若干水果单词组成的字符串数组,统计有多少种水果
时间: 2024-02-18 20:02:27 浏览: 38
您好!对于您的问题,我可以提供以下Java代码来统计水果种类:
```java
String[] fruits = {"apple", "banana", "orange", "apple", "pear", "orange", "banana"};
Set<String> fruitSet = new HashSet<>(Arrays.asList(fruits));
int fruitCount = fruitSet.size();
System.out.println("There are " + fruitCount + " kinds of fruits.");
```
这段代码中,我们将字符串数组转换为Set集合,由于Set集合不允许重复元素,因此最终fruitSet的大小即为水果种类数。输出语句将结果打印到控制台。
希望能够帮到您!
相关问题
Java设有一个含若干水果单词组成的字符串数组,String[] fruits = {"apple", "pear", "apple", "apple","orange","pear", "apple"};编程统计有多少种水果
可以使用一个 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
```
java 设有一个含若干水果单词组成的字符串数组,编程统计该数组中共有多少种水果。假设调试的数据如下: String fruit[]= { "apple","pear","apple","apple","orange","pear","apple"};
好的,你的问题是统计含若干水果单词组成的字符串数组中共有多少种水果。针对你给出的调试数据,我可以给出以下 Java 代码实现:
```java
public class CountFruits {
public static void main(String[] args) {
String fruit[] = {"apple", "pear", "apple", "apple", "orange", "pear", "apple"};
Set<String> set = new HashSet<String>();
for (int i = 0; i < fruit.length; i++) {
set.add(fruit[i]);
}
System.out.println("该数组中共有 " + set.size() + " 种水果");
}
}
```
代码中我们使用了 `HashSet` 来统计不同的水果种类数,`HashSet` 特点是不允许重复元素,所以将数组中的元素加入到 `HashSet` 中,最后统计 `HashSet` 的大小即可得到水果种类数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)