Write an application that will simulate a coin toss Use the

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

Solution

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

*/

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 r
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 r

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site