// 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 gotHeads // method. import java.util.*; public class GamesOfChance { public static void main(String[] args) { Random rand = new Random(); for (int i = 0; i < 5; i++) { System.out.println(countHeads(10, rand)); } System.out.println(); for (int i = 0; i < 5; i++) { // Bad Boolean zen - DON'T DO THIS!! // if (gotHeads(3, rand)) == true) { if (gotHeads(3, rand)) { System.out.println("Found a heads!"); } } System.out.println(); } // Write a method countHeads that takes an integer and a Random // object as parameters and simulates flipping a coin the given // number of times. The method hsould return the number of flips // that came up "heads." // // int numFlips - the maximum number of times to flip // Random rand - the Random object to use for randomization public static int countHeads(int numFlips, Random rand) { int numHeads = 0; for (int i = 0; i < numFlips; i++) { int flip = rand.nextInt(2); if (flip == 0) { numHeads++; } } return numHeads; } // Write a method gotHeads that takes an integer and a Random // object as parameters and simulates flipping a coin at most // the given number of times. The method should return true // if at least one flip comes up "heads" and false if all flips // come up "tails." // // int numFlips - the maximum number of times to flip // Random rand - the Random object to use for randomization public static boolean gotHeads(int numFlips, Random rand) { for (int i = 0; i < numFlips; i++) { int flip = rand.nextInt(2); if (flip == 0) { // 0 -> heads, 1 -> tails return true; } } return false; } }