(Intro to Java help?) Write a complete program that plays a coin flipping game,
ID: 3724345 • Letter: #
Question
(Intro to Java help?)
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)
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
FlipCoin.java
public class FlipCoin {
public static void main(String[] args) {
int h=0, t=0,n=0;
while(h!=3 && t!=3) {
n++;
char ch = flip();
System.out.println(ch);
if(ch=='H'){
h++;
t=0;
} else {
t++;
h=0;
}
}
System.out.println("Number of flips: "+n);
}
public static char flip() {
int r = (int)(Math.random()*2);
if(r==0) {
return 'H';
}
return 'T';
}
}
Output:
H
T
T
H
T
T
T
Number of flips: 7
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.