HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

"Consecutive Heads" program

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
programheadsconsecutive

Problem

So... I have a program in which I want to flip heads three times in the row.

What I'm asking for is for proposals of other solutions for this program, in pro way, as You do in natural sense.

That's my code as Java novice.

/*
 * File: ConsecutiveHeads.java
 * ----------------
 * This program flips a coin repeatly until three consecutive heads
 * are tossed.
 */

import acm.program.*;
import acm.util.*;

public class ConsecutiveHeads extends ConsoleProgram {
    /* Run the program */
    public void run() {
        println("This program flips a coin until there are three" +
                "heads in the row.");
        while(counter != 3) {
            FlipACoin();
        }
        println("Yupii! There are already three same heads in the row :)");
    }

    /* Flip a coin. Then if heads are tossed, increment our counter.
     * In tails case, zero counter. */
    private void FlipACoin() {
        boolean rank = rgen.nextBoolean();
        if(rank) {
            println("heads");
            counter++;
        } else {
            println("tails");
            counter = 0;
        }
    }

    /* Create an instance variable for the random number generator */
    private RandomGenerator rgen = new RandomGenerator();

    /* Create an instance variable for counter detecting three heads in row */
    private int counter = 0;
}

Solution

Your function is called FlipACoin(), but you are doing more than just flipping the coin. A more appropriate name might be FlipACoinAndCountConsecutiveHeadRolls().

I would suggest keeping the function as simple as the name suggests and return a string (or boolean) from FlipACoin(), then examine the result outside the function. This will also allow you to make the counter a local variable to the run function, which will make the class smaller.

Context

StackExchange Code Review Q#855, answer score: 4

Revisions (0)

No revisions yet.