Java设有一个含若干水果单词组成的字符串数组,编程统计该数组中共有多少种水果。 假设调试的数据如下: String fruit[]= { "apple","pear","apple","apple","orange","pear","apple","peach"};
时间: 2024-06-16 15:01:25 浏览: 12
在Java中,要统计一个字符串数组中不同元素(即不同种类的水果)的数量,你可以使用`HashSet`或`HashMap`来存储并计算元素数量,因为`HashSet`不允许有重复的元素。这里我将展示如何使用`HashSet`来完成这个任务:
```java
import java.util.HashSet;
public class FruitCounter {
public static void main(String[] args) {
String[] fruit = {"apple", "pear", "apple", "apple", "orange", "pear", "apple", "peach"};
// 使用HashSet存储不重复的水果
HashSet<String> uniqueFruits = new HashSet<>(Arrays.asList(fruit));
// 计算和输出不同种类的水果数量
int distinctFruitCount = uniqueFruits.size();
System.out.println("Array contains " + distinctFruitCount + " different types of fruits.");
}
}
```
运行这段代码后,你会得到输出,例如:"Array contains 4 different types of fruits."
相关问题
Java设有一个含若干水果单词组成的字符串数组,统计有多少种水果
您好!对于您的问题,我可以提供以下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 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` 的大小即可得到水果种类数。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)