Write a program BoysAndGirlsjava that takes an integer comma

Write a program BoysAndGirls.java that takes an integer command-line argument T. In each of T independent experiments, simulate a couple having children until they have at least one of each gender. Use the results of the T experiments to estimate the average number of children the couple will have. Record and output the frequency counts for 2, 3, and 4 children, and also one count for 5 and above. Finally, output the most common number of children in a family. (If there is a tie, print only the first most common number of children.) As before, assume that the probability of having a boy or a girl is 1/2.

Solution

import java.util.Random;
public class BoysAndGirls{
    public static void main(String[] args) {
        int T = Integer.parseInt(args[0]);
        int num[] = new int[T];
        int freq[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        int total = 0;
        double avg;
        for (int i=0; i<T; i++){
            int boycount = 0;
            int girlcount = 0;
            while(girlcount==0 || boycount==0){
                Random rand = new Random();
                int x = rand.nextInt(2);
                if (x==0){
                    boycount ++;
                }
                else{
                    girlcount ++;
                }
            }
            num[i] = boycount + girlcount;
            total += boycount + girlcount;
            freq[boycount+girlcount-2] ++;
        }
        avg = total*1.0/T;
        int count2 = freq[0];
        int count3 = freq[1];
        int count4 = freq[2];
        int count5ormore = T - (count2 + count3 + count4);
        int maxindex = -1;
        int max = 0;
        for (int i = 0; i<freq.length; i++){
            if(freq[i]>max){
                max = freq[i];
                maxindex = i;
            }
        }
        int mode = maxindex+2;

        System.out.println(\"Average number of children a couple will have: \"+avg);
        System.out.println(\"Frequency counts for 2 children: \"+count2);
        System.out.println(\"Frequency counts for 3 children: \"+count3);
        System.out.println(\"Frequency counts for 4 children: \"+count4);
        System.out.println(\"Frequency counts for 5 or more children: \"+count5ormore);
        System.out.println(\"Most common number of children in a family: \"+mode);
    }
}

Write a program BoysAndGirls.java that takes an integer command-line argument T. In each of T independent experiments, simulate a couple having children until t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site