PLEASE ANSWER ASAP!!! IN JAVA PLEASE Write a complete program that plays a coin
ID: 3829282 • Letter: P
Question
PLEASE ANSWER ASAP!!!
IN JAVA PLEASE
Write a complete program that plays a coin flipping game, displays the individual flips, reports when a game is “LOST” or “WON” and shows the number of flips needed to complete the game.
The algorithm is as follows:
• Simulate the flip of a coin using a JAVA random number generator.
• Flip the coin once to initialize the flip value and print out the flip
• Inside of a loop, repeatedly flip the coin until 3 consecutive flips have the same value (3 heads or 3 tails)
a. Display the flip results after each flip
• When the game ends, report the total number of flips
Note: you can use 0 for heads and 1 for tails, but if you have time, add another method that will convert the integers 0 and 1 to the characters ‘H’ and ‘T
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Random;
public class CoinFlip {
public static void main(String[] args) {
Random rand = new Random();
int head = 0, tail = 0, total = 0;
while(true){
int num = rand.nextInt(2); // 0 or 1
total++;
if(num == 0){
head++;
tail = 0;
System.out.println("Flip value: H");
// 3 consicutive head
if(head == 3)
break;
}else{
tail++;
head = 0;
System.out.println("Flip value: T");
// 3 consicutive tail
if(tail == 3)
break;
}
}
System.out.println("Total flips: "+total);
}
}
/*
Sample run:
Flip value: H
Flip value: T
Flip value: T
Flip value: T
Total flips: 4
Flip value: H
Flip value: T
Flip value: H
Flip value: H
Flip value: T
Flip value: H
Flip value: H
Flip value: T
Flip value: T
Flip value: T
Total flips: 10
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.