I am doing exercises for the Art and Science of Java textbook. I had an exercise that required me to program the simulation of flipping a coin until 3 consecutive "Heads" result appeared.
I did it, but I'm not sure if my code is simple enough - since I used an instance variable to count the heads and a function that not only flips the coins but counts the consecutive heads as well.
I avoided placing too much lines in the run method (the main method since im using acm libraries) but i'm not sure if this is the most efficient coding.
Here's the code:
import acm.program.*;
import acm.util.*;
public class ConsecutiveHeads extends ConsoleProgram {
private static final int CONSECUTIVE_HEADS_LIM = 3;
public void run () {
int nFlips = 0;
while (nConsecutiveHeads < CONSECUTIVE_HEADS_LIM) {
flipCoin();
nFlips++;
}
println ("You needed " + nFlips + " flips to get " + CONSECUTIVE_HEADS_LIM + " Consecutive Heads.");
}
private void flipCoin () {
String coinFace = rgen.nextBoolean() ? "Heads" : "Tails";
if (coinFace.equals("Heads")) {
nConsecutiveHeads++;
} else if (coinFace.equals("Tails")){
nConsecutiveHeads = 0;
}
println (coinFace);
}
private int nConsecutiveHeads = 0;
private RandomGenerator rgen = RandomGenerator.getInstance();
}