Java—统计每一个数字在数组中出现的次数
/*需求
* 定义长度为10的int型数组,
* 数组元素的值的范围是0-9,
* 由随机数随机产生,打印输出该数组的值,
* 并统计每一个数字在数组中出现的次数*/
public class RandomArray {
public static void main(String[] args) {
//动态创建数组
int[] array=new int[10];
//创建Random实例
Random random =new Random();
for (int i = 0; i < array.length; i++) {
//调用random的nextInt方法 生成随机数
int num = random.nextInt(10);//0-9
//将随机数存放在数组中
array[i]=num;
System.out.print(array[i]+" ");
}
定义数组用于存放0到9之间的每一个数字出现的次数
int[] count=new int[array.length];
//开始统计 0到9中每一个数字在数组中出现了多少次
for (int i = 0; i <=9; i++) {
for (int j = 0; j < array.length; j++) {
if (i==array[j]){
count[i]++;
}
}
}
//遍历输出
for (int i = 0; i <=9; i++) {
System.out.println(i+"共出现了:"+count[i]+"次");
}
}
}