Write a program BoysAndGirls.java that takes an integer command-line argument T
ID: 3544491 • Letter: W
Question
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. As T increases, we expect the average number of children per family to converge. Use BoysAndGirls to formulate a hypothesis as to what this average is. Run BoysAndGirls with T = 1, 10, 100, 100000 and 1000000 to watch it converge to a sufficiently accurate estimate.
Explanation / Answer
Code
public class BoysAndGirls {
public static void main(String[] args) {
int input = 0;
if (args.length > 0) {
try {
input = Integer.parseInt(args[0]);
}
catch (NumberFormatException e) {
System.err.println("Given argument" + " must be an integer");
System.exit(1);
}
}
int countOfChildren = 0;
int numberOfFamiliesWithTwo = 0;
int numberOfFamiliesWithThree = 0;
int numberOfFamiliesWithFour = 0;
int numberOfFamiliesWithFiveAndMore = 0;
float totalKidsMultipliedFrequency = 0;
float average = 0;
for (int i =0; i < input; i++){
BoysAndGirls boysAndGirls = new BoysAndGirls();
countOfChildren =boysAndGirls.findNumberOfChildren();
if (countOfChildren== 2){
numberOfFamiliesWithTwo++;
}
else if (countOfChildren == 3){
numberOfFamiliesWithThree++;
}
else if (countOfChildren == 4){
numberOfFamiliesWithFour++;
}
else if (countOfChildren >=5){
numberOfFamiliesWithFiveAndMore++;
}
}
totalKidsMultipliedFrequency +=(2 * numberOfFamiliesWithTwo)+(3 * numberOfFamiliesWithThree)+ (4 * numberOfFamiliesWithFour)
+ (5 * numberOfFamiliesWithFiveAndMore);
average = totalKidsMultipliedFrequency/input;
System.out.println("Average: "+average+" children to get at least one of each sex.");
System.out.println("Number of families with 2 children: "+numberOfFamiliesWithTwo);
System.out.println("Number of families with 3 children: "+numberOfFamiliesWithThree);
System.out.println("Number of families with 4 children: "+numberOfFamiliesWithFour);
System.out.println("Number of families with 5 or more: "+numberOfFamiliesWithFiveAndMore);
}
public int findNumberOfChildren()
{
int countOfBoys = 0;
int countOfGirls = 0;
int countOfChildren = 0;
while(countOfBoys <1 || countOfGirls < 1 ){
boolean flag = Math.random() < 0.5;
if(flag){
countOfBoys++;
countOfChildren++;
}
else{
countOfGirls++;
countOfChildren++;
}
}
return countOfChildren;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.