统计随机数的个数

/* 随机生成50个整数,每个数字的范围是[10,50],统计每个数字出现的次数以及
 * 出现次数最多的数字与它的个数,最后将每个数字及其出现次数打印出来。如果
 * 某个数字出现的次数为0,则不要打印它.
 * java.lang.Math;-----random();方法
 *
 * java.util.Random;
 *
 * */

public class NumberTest1
{
	public static void main(String[] args)
	{
		//随机生成[10,50]之间的50个整数。并放在数组中。
		int[] arr = new int[50];

		for(int i = 0; i < arr.length; i++ )
		{
			arr[i] = (int)(Math.random()*41)+10;
			if(i % 10 == 0)
				System.out.println();//每行按10个输出。
			System.out.print(arr[i]+" ");
		}

		System.out.println();
		
		int[] counts = numCount(arr);//调用方法
	
	
		//统计每个数字出现的个数。
		for(int j = 0; j < counts.length; j++)
		{
		//	System.out.println(counts.length);  //out:41
		//	判断:
			if(counts[j]!=0)
			{	
				System.out.println((10+j)+"出现了"+counts[j]+"次");
			}
		}

		//将出现次数最多的数字打印。
		int max = counts[0];
		for(int n = 0; n <counts.length;n++)
		{
			if(counts[n]>max)
			{
				max = counts[n];
			}
		
		}

		System.out.println("最多出现了"+max+"次");

		for(int j = 0;j < counts.length;j++)
		{
			if(counts[j] == max)
				System.out.println("出现次数最多的值为:"+(j+10));
		}
	}


	public static int[] numCount(int[] arr)//返回数组int[]
	{
		int[] count = new int[41];//最多出现41种
		for(int i = 0; i < arr.length; i++)
		{
			count[arr[i]-10]++;//arr[i]的值-10作为count的下标。
		}
		
		return count;//返回数组名,可以得到每个数字出现的次数。
	}
	
} 			 			}	
		
 /*
public static void main(String[] args)
{
	int[] count = new int[41];
	Random r = new Random();

	for(int i=0;i<50;i++)
	{
		int number = random.nextInt(41)+10;//[10,50]

		count[number-10]++;
	
	}

	for(int j = 0;j < count.length;j++)
	{
		if( count[j] != 0)
			System.out.println((10+j)+"出现了"+count[i]+"次");
	}
}
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值