Write an application that will perform a series of coin tosses and display the p
ID: 674181 • Letter: W
Question
Write an application that will perform a series of coin tosses and display the percentage of heads and tails. Prompt the user to input the number of desired coin tosses Use the Math.random() function to generate a random number between 0 and 1. If the value is 0.5 or less, the result represents a head; otherwise, it represents a tail. After you have tossed the coin the desired number of times based on the user input, dispay the percentage of heads and tails. Run the application several times until you are confident that the coin tosses occur randomly and your calculations are correct.
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
public class CoinToss
{
public static void main (String[] args)
{
int toss;
int counter;
int heads, tails;
counter = 0;
heads = 0;
tails = 0;
Scanner input=new Scanner(System.in);
System.out.println("Enter amount of times you want the coin to be tossed :");
toss=input.nextInt();
Random coinToss = new Random();
int random = coinToss.nextInt(1);
while (counter < toss)
{
if (random > 0.5)
{
heads = heads + 1;
System.out.println("Head");
}
else
{
tails = tails + 1;
System.out.println("Tail");
}
counter++;
random = coinToss.nextInt(2);
}
System.out.println("");
System.out.println("For your tosses you got " + "------------------- " + "Heads: " + heads + " Tails: " + tails);
} // end main
} // end class CoinToss
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.