随机整数数组中每个值的频率



需要帮助的分配,我必须生成1到6之间的随机运行30个球,并得到:1.总得分2.0、1、2、3、4、6的个数3.罢工率

虽然我有"总运行"one_answers"命中率",但我无法获得0,15的频率…我试过使用计数器和流方法,但似乎不能得到它的权利。非常感谢你的帮助。谢谢你!

这里是实际的代码,我已经将频率部分标记为block,这样至少其他方法可以执行…

import java.util.Random;
public class Assignment_2 {
    
    public static void main(String[] args) {
        Random r = new Random();
        System.out.println("Runs for 30 balls");
        int ball[] = new int[30];
        for(int i=0; i<ball.length; i++)
        {
            ball[i] = r.nextInt(6);
            System.out.print(ball[i]+" , ");**
         
    /*  int zeros = 0;
        int ones = 0;
        int twos = 0;
        int threes = 0;
        int fours = 0;
        int fives = 0;
        int sixes = 0;
            if (r.nextInt() == 0 ) {
                zeros++;
            } 
            else if (r.nextInt() == 1) {
                ones++;
            } 
            else if (r.nextInt() == 2) {
                twos++;
            }
            else if (r.nextInt() == 3) {
                threes++;
            }
            else if (r.nextInt()== 4) {
                fours++;
            }
            else if (r.nextInt() == 5) {
                fives++;
            }
            else if (r.nextInt() == 6) {
                sixes++;
            }
            System.out.println(zeros);
            System.out.println(ones);
            System.out.println(twos);
            System.out.println(threes);
            System.out.println(fours);
            System.out.println(fives);
            System.out.println(sixes);
    */
        **}
        
        System.out.println();
        
        System.out.println("Runs Scored");
        float TR=0;
        for(int i : ball)
        {
            TR += i;
        }  
        System.out.print(TR);
        
        System.out.println();
        
        System.out.println("Strike Rate");
        float SR=(TR/30)*100;
        System.out.print(SR);
        
        System.out.println();
        
        
    }
}
 if (r.nextInt() == 0 )

等比较新生成的随机数。您想要比较已经用于球的内容:

if ( ball[i] == 0 ) ..等等,尽管使用数组来存储计数而不是单独的变量会更简洁和更少的代码。

最新更新