Write a Java program Name FlipMyCoin that simulates flipping coins and counts th
ID: 3931203 • Letter: W
Question
Write a Java program Name FlipMyCoin that simulates flipping coins and counts the coin flips. The program should ask the user how many times to flip the coin, then simulate flipping the coin that many times (using a random number generator), prints a symbol (H or T) for each coin flip, and provides a summary giving the total number of heads and tails. Guide As always, your program should first output an introductory message to the user explaining what the program does. Then prompt the user to enter the number of coins to flip. The program will need a loop, and the instructions inside the loop should deal with flipping the coin once. You can simulate the coin flip with a random number generator. One way to do that in Java is to use the Math. Random method. When you need to simulate a coin flip, you call the Math. Random method to generate a random number x between 0 and 1 (greater than or equal to 0, but strictly less than 1). This random number has a uniform distribution, so the probability that it's less than 0.5 is one half. The condition to randomize If (Math. Random()Explanation / Answer
FlipMyCoin.java
import java.util.Scanner;
public class FlipMyCoin {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("***Welcome to Flip My Coin***");
while(true){
System.out.print("Enter how many items to flip the coin: ");
int n = scan.nextInt();
int heaCount =0, tailCount = 0;
for(int i=0; i<n; i++){
int toss = (int )(Math. random() * 2);
if(toss == 1){
System.out.println("H");
heaCount++;
}
else{
System.out.println("T");
tailCount++;
}
}
System.out.println("Head Count: "+heaCount);
System.out.println("Tail Count: "+tailCount);
System.out.print("Do you want to continue (y or n): ");
char ch = scan.next().charAt(0);
if(ch == 'n'|| ch=='N'){
break;
}
}
}
}
Output:
***Welcome to Flip My Coin***
Enter how many items to flip the coin: 10
H
H
H
T
T
H
T
T
H
H
Head Count: 6
Tail Count: 4
Do you want to continue (y or n): y
Enter how many items to flip the coin: 5
T
H
H
T
H
Head Count: 3
Tail Count: 2
Do you want to continue (y or n): n
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.