Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Help with JAVA code using loops: A couple beginning a family decides to keep hav

ID: 3794767 • Letter: H

Question

Help with JAVA code using loops:

A couple beginning a family decides to keep having children until they have at least one of each sex.

Write code that simulates repeatedly having a child until there is at least one of each sex. Output how many children it took to achieve this goal. Assume there is an equal probability of having either a boy or a girl. Use a while loop to compute the number of children the couple has until getting at least one of each gender.

//output should look like this

Congratulations! You have 1 boy(s) and 1 girl(s).

Congratulations! You have 1 boy(s) and 3 girl(s).

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

import java.util.Random;

public class BabySimulation {

   public static void main(String[] args) {

      

       // creating Random obeject

       Random random = new Random();

      

       int girls = 0;

       int boys = 0;

      

       // GENERATING RANDOM NUMBER: 0 - Boy, 1-Girl

      

       while(girls == 0 || boys == 0){

          

           int rand = random.nextInt(2); // generating random number 0,1

           if(rand == 0)

               boys++;

           else

               girls++;

       }

      

       System.out.println("Congratulations! You have "+boys+" boy(s) and "+girls+" girl(s).");

   }

}

/*

Sample run:

Congratulations! You have 1 boy(s) and 2 girl(s).

Congratulations! You have 1 boy(s) and 1 girl(s).

Congratulations! You have 2 boy(s) and 1 girl(s).

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote