Java输入数组找出出现次数最多的数
时间: 2024-04-29 12:24:21 浏览: 9
以下是一个示例程序,它接受用户输入的整数数组并找出出现次数最多的数字:
```
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = input.nextInt();
int[] arr = new int[size];
System.out.print("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
// Find the most frequently occurring number
int maxCount = 0;
int maxNum = arr[0];
for (int i = 0; i < size; i++) {
int count = 1;
for (int j = i+1; j < size; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxNum = arr[i];
}
}
System.out.println("The most frequently occurring number is: " + maxNum);
System.out.println("It occurs " + maxCount + " times.");
}
}
```
该程序首先要求用户输入数组的大小和元素,然后使用嵌套循环来计算每个数字出现的次数。最后,它找到出现次数最多的数字并输出它以及它出现的次数。