Thursday, November 1, 2012

Coin Toss Example

While this isn't the way we would probably have approached the coin toss project, this one is interesting because it tallies up the number of heads and tails we get out of 100 coin flips.  This code involves using a counter, a Math.random number generator (0 or 1 is the result), a counter for the results of each of the sides of the coin, and a "do while" loop.  Study the code and see if you can figure out what the unfamiliar code pieces are doing.

class Toss {
        public final int HEADS = 0;
        static int countH = 0;
        static int countT = 0;
        static int counter = 0;
        private static int face;

        public static void flip() {
                face = (int) (Math.random() * 2);
        }

        public String toString() {
                String faceName;
                counter++;
                if (face == HEADS) {
                        faceName = "Heads";
                        countH++;
                } else {
                        faceName = "Tails";
                        countT++;
                }
                return faceName;
        }

        public static void main(String[] args) {
                System.out.println("Outcomes:");
                do {
                        flip();
                        System.out.println(new Toss().toString());
                } while (counter < 100);
                System.out.println("Number of Tails: " + countT);
                System.out.println("Number of Heads: " + countH);
        }
}

No comments:

Post a Comment