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

Create a CoinToss application with a static method flip that returns either 0 fo

ID: 3690352 • Letter: C

Question

Create a CoinToss application with a static method flip that returns either 0 for tails or 1 for heads. Use the SecureRandom class to simulate the coin flip. In main you will ask the player how many times s/he wants to flip the coin. Use a for loop to play the game that many times.

For each game ask the player if they want heads (1) or tails (0) and then flip the coin. If the player enters anything but 1 or 0 you must keep prompting until they enter 1 or 0. Use a do-while loop to do this. For each coin flip you must tell the player the result and if s/he won or lost. After the coin flipping stops (after the for loop) you must tell the player how many times s/he guessed correctly out of the total number of coin flips.

Explanation / Answer

import java.util.*;

class SecureRandom
{
   public static int flip()
   {
       Random r = new Random();
       int c = r.nextInt(2)+0;
       return c;
   }

   public static void main(String args[])
   {
       int n,a,ans,b=0;
       Scanner scan = new Scanner(System.in);

       System.out.println("Enter how many times you play game");
       n=scan.nextInt();

       for(i=0;i<n;i++)
       {
           a=flip();
           System.out.println("Enter your choice");
           ans=scan.nextInt();

           if(a==ans)
           {
               System.out.println("You won");
               b++;
           }
           else
           {
               System.out.println("You Loss");
           }
       }
       System.out.println("You won "+b+" Times");
   }
}