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

Write an application that will simulate a coin toss. Use the Math.random() funct

ID: 3929660 • Letter: W

Question

Write an application that will simulate a coin toss. Use the Math.random() function for the coin toss:

For the toss you may use the following criteria: if the result is 0.5 or less, the toss represents a head, otherwise it represents a tail.

Have a user input to determine how many tosses of the coin is desired. Generate the tosses and keep track of the number of heads and number of tails (do not display each toss). Display the percentage of heads and tails after the tosses are complete

Save the application as FlipCoin.java

Explanation / Answer

Hi, Please find my implementation.

Please let me know in case of any issue.

import java.util.Scanner;

public class FlipCoin {

  

   public static void main(String[] args) {

      

       // Scanner Object to take user input

       Scanner sc = new Scanner(System.in);

      

       System.out.print("How many tosses of the coin is desired: ");

       int n = sc.nextInt();

      

       int head = 0;

       int tail = 0;

      

       int i = 1;

       while( i<= n){

           double rand = Math.random();

           if(rand <= 0.5)

               head++;

           else

               tail++;

           i++;

       }

      

       //calculating percentage

       double headPer = (double)head/(head+tail)*100;

       double tailPer = (double)tail/(head+tail)*100;

      

       // displaying 2 decimal points

       System.out.println("% of head: "+String.format("%.2f", headPer));

       System.out.println("% of tail: "+String.format("%.2f", tailPer));

   }

}

/*

Sampler run:

How many tosses of the coin is desired: 7

% of head: 42.86

% of tail: 57.14

*/

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