In: Computer Science
Write a program to toss a coin multiple times. Ask the user for how many times to toss the coin and then display the percentage of heads and tails (do not display each toss, just the totals). JAVA
JAVA Program:
import java.io.*;
import java.util.*;
class Toss {
public static void main (String[] args) {
int count,headcount=0,tailcount=0,toss;
System.out.print("Enter the number
of times to toss the coin: ");
Scanner sc = new
Scanner(System.in);
count = sc.nextInt();
Random rand = new Random();
//0 -- head 1 -- tail
for(int i=0;i<count;i++){
toss = rand.nextInt(2);
if(toss==0)
headcount++;
else
tailcount++;
}
System.out.println("Total head
count is "+headcount);
System.out.println("Total tail
count is "+tailcount);
System.out.printf("Percentage of
heads is %.2f\n",(float)headcount/(float)count);
System.out.printf("Percentage of
tails is %.2f",(float)tailcount/(float)count);
}
}
Output: