In: Computer Science
Write a program that simulates the flipping of a coin n times, where n is specified by the user. The program should use random generation to flip the coin and each result is recorded. Your program should prompt the user for the size of the experiment n, flip the coin n times, display the sequence of Heads and Tails as a string of H (for Head) and T (for Tail) characters, and display the frequencies of heads and tails in the experiment. Use functions for full credit.
import java.util.*;
class Main
{
public void toss(int n)
{
int count1=0,count2=0;
String a[]=new String[n];
Random random = new Random();
for(int i=0;i<n;i++)
{
int rnd = random.nextInt(2);
if(rnd==0)
{
a[i]="T";
count1++;
}
if(rnd==1)
{
a[i]="H";
count2++;
}
}
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.println("\nThe frequency of Heads is "+count2);
System.out.println("The frequency of Tails is "+count1);
}
public static void main(String args[])
{
Main m=new Main();
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of time you want to toss a coin : ");
int n=sc.nextInt();
m.toss(n);
}
}
Here is the program that uses random integer generator that will ask the user for n value and give it to a function then uses random value for n times and generate H and T and store them in the array and then finally print the freqencies of head and tails and then print the array of randomly generated H and T.
SCREENSHOT OF THE OUTPUT :
*************************************************PLEASE DO UPVOTE********************************************************