java编写一个程序,读取个数不定的整数,然后查找其中出现频率最高的数字。当输入为0时,表示结束输入。例如,如果输入的数据是 29 7 8 3 6 6 -6 4 5 6 1 0,那么数字6的出现频率最高。如果出现频率最高的数字不止一个,则应该将它们全部输出。例如,在线性表9 30 3 9 3 2 4中,3和9都出现了两次,所以3和9都应该被输出
时间: 2023-12-08 12:04:51 浏览: 27
好的,以下是用 Java 语言编写的程序:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> nums = new ArrayList<>();
while (true) {
System.out.print("请输入一个整数(输入0结束输入):");
int num = input.nextInt();
if (num == 0) {
break;
}
nums.add(num);
}
Map<Integer, Integer> count = new HashMap<>();
for (int num : nums) {
count.put(num, count.getOrDefault(num, 0) + 1);
}
int maxCount = Collections.max(count.values());
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
if (entry.getValue() == maxCount) {
result.add(entry.getKey());
}
}
System.out.print("出现频率最高的数字是:");
for (int num : result) {
System.out.print(num + " ");
}
}
}
```
程序的思路跟 Python 版本的程序类似,具体如下:
1. 首先,通过一个循环,读取用户输入的整数,并将它们存储在一个列表中。
2. 接着,我们遍历这个列表,使用一个 Map 来记录每个数字出现的次数。
3. 最后,我们找到出现次数最多的数字,并将它们全部输出。
需要注意的是,如果有多个数字出现的次数都是最多的,那么程序会将它们全部输出。