In java please, Write e a program called CoinFlip that simulates flipping a coin
ID: 3724499 • Letter: I
Question
In java please,
Explanation / Answer
Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.
// CoinFlip.java
import java.util.Random;
public class CoinFlip {
static Random random;
public static void main(String[] args) {
/**
* Initializing the Random object
*/
random = new Random();
/**
* consecutiveHeads keep the track of consecutive Heads count
*/
int consecutiveHeads = 0, flips = 0;
/**
* loops until 3 consecutive heads are drawn
*/
while (consecutiveHeads != 3) {
/**
* flipping the coin
*/
String headsOrTails = flipCoin();
/**
* Displaying Heads or Tails
*/
System.out.println(headsOrTails);
/**
* incrementing the count of flips
*/
flips++;
if (headsOrTails.equals("Heads")) {
/**
* incrementing the count of consecutive heads in case of
* "Heads"
*/
consecutiveHeads++;
} else {
/**
* resetting the count of consecutive heads to 0 if a "Tails" is
* drawn
*/
consecutiveHeads = 0;
}
}
/**
* Displaying the stats
*/
System.out.println("It took " + flips
+ " flips to get 3 consecutive heads.");
}
/**
* a method to simulate random coin flipping
*
* @return - either "Heads" or "Tails"
*/
static String flipCoin() {
/**
* random.nextBoolean() will return either true or false, if it is true,
* this method return "Heads", else "Tails"
*/
if (random.nextBoolean()) {
return "Heads";
} else {
return "Tails";
}
}
}
/*OUTPUT*/
Tails
Tails
Tails
Heads
Heads
Tails
Tails
Tails
Heads
Heads
Tails
Tails
Heads
Tails
Tails
Tails
Heads
Heads
Heads
It took 19 flips to get 3 consecutive heads.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.