5.2 编写程序,随机产生1000个1-6的整数。统计每个数出现的次数,修改程序,使之产生1000个1-6的随机数,并统计每个数出现的次数。 比较不同的结果并给出结论。

该博客展示了如何使用Java编程生成1000个1-6的随机数并统计每个数字出现的频率。通过两种方法实现:一种是传统的if语句,另一种是使用switch语句。结果显示了每种方法的统计结果,验证了随机数的均匀分布特性。此外,还对比了if和switch在处理此类问题时的效率和代码可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package bookTest2;

public class FivePointTwo {
    /*
    编写程序,随机产生1000个1-6的整数。统计每个数出现的次数,修改程序,使之产生1000个1-6的随机数,并统计每个数出现的次数。
    比较不同的结果并给出结论。
    1.随机数1-6 一共随机产出1000位
    2.比较每个数出现的次数 得出结论
     */
    public static void main(String[] args) {
        //1.建立一个数组 存放这1000个整数
        int[] arr = new int[1000];
        int count1=0,count2=0, count3=0,count4=0,count5=0,count6=0, bottom =0, count= 0;
        for (int i = 0; i <arr.length ; i++) {
           arr[bottom] = (int)( Math.random()*6)+1;
            bottom++;
            if (arr[i]== 1) {
                count1++;
            }
            if (arr[i]== 2) {
                count2++;
            }
            if (arr[i]== 3) {
                count3++;
            }
            if (arr[i]== 4) {
                count4++;
            }
            if (arr[i]== 5) {
                count5++;
            }
            if (arr[i]== 6) {
                count6++;
            }
        }
        System.out.println("输出随机数为1的有 "+count1);
        System.out.println("输出随机数为2的有 "+count2);
        System.out.println("输出随机数为3的有 "+count3);
        System.out.println("输出随机数为4的有 "+count4);
        System.out.println("输出随机数为5的有 "+count5);
        System.out.println("输出随机数为6的有 "+count6);
        System.out.println("一共多少次"+(count1+count2+count3+count4+count5+count6));

        for (int i = 0; i <arr.length ; i++) {
            System.out.print(arr[i]+" ");
            count++;
            if (count%100==0) {
                System.out.println();
            }
        }
    }
}

运行结果图

方法二 把条件换成switch 语句

   public static void main(String[]args){
		 int[] rand=new int[6];
		 for(int i=0;i<1000;i++){
		   int r=(int)(Math.random()*6)+1;
		   switch(r){
		  	 case 1: rand[0]++;break;
		  	 case 2: rand[1]++;break;
		  	 case 3: rand[2]++;break;
		  	 case 4: rand[3]++;break;
		  	 case 5: rand[4]++;break;
		  	 case 6: rand[5]++;break;
		   }	
		 }
		
		 for(int i=0;i<rand.length;i++)
		    System.out.println("rand["+i+"]="+rand[i]);	  
	   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值