Skip to content
Advertisement

Frequency of each value in an array of random integers

Need help with an assignment where I have to generate random runs between 1 to 6 for 30 balls and get : 1.Total runs scored 2.Number of 0s, 1s, 2s, 3s, 4s and 6s 3.Strike Rate

While I have got ‘Total runs’ and ‘Strike rate’, I am unable to get the frequency of 0s,1s… I have tried using counter and stream method, but can’t seem to get it right. Your help is highly appreciated. Thank you!

And here’s the actual code, I have marked the frequency part as block for now so that atleast other methods execute…

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();
        
        
    }
}

Advertisement

Answer

 if (r.nextInt() == 0 )

etc is comparing a newly generated random number. You want to compare what is already used for the ball:

if ( ball[i] == 0 ) .. etc. although using an array to store the counts instead of individual variables would be cleaner and less code.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement