// This program demonstrates some basic usage of booleans types // and values. Notice the use of good "Boolean zen" and the // "innocent until proven guilty" pattern in the flipCoin // method. import java.util.*; public class CoinFlips { public static void main(String[] args) { int count = 0; for (int i = 0; i < 1000; i++) { boolean result = flipCoin(5); // bad Boolean Zen - DON'T DO THIS!! // if (result == true) { // count ++; // } if (result) { count++; } } // analysis } // Write a method flipCoin that takes a single integer parameter // and simulates flipping a coin at most that many times. The // method should return true if at least one flip comes up "heads" // and false if all flips come up "tails." // // int numTries - the maximum number of times to flip public static boolean flipCoin(int numTries) { Random rand = new Random(); for (int i = 1; i <= numTries; i++) { int flip = rand.nextInt(2); // 0 = heads, 1 = tails if (flip == 0) { return true; } } return false; // assert: NEVER have flipped heads } }