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

Frequency of each value in an array of random integers

需要帮助完成一项任务,我必须为 30 个球生成 1 到 6 之间的随机运行并得到: 1.Total 得分 2.Number 个 0、1、2、3、4 和 6 3.Strike评分

虽然我有 'Total runs' 和 'Strike rate',但我无法获得 0s、1s 的频率... 我试过使用 counter 和 stream 方法,但似乎无法正确使用。 非常感谢您的帮助。 谢谢!

这是实际的代码,我暂时将频率部分标记为块,以便至少执行其他方法...

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 )

etc 正在比较新生成的随机数。您想比较球已经使用的东西:

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