A Java Course Outline
Using the Java By Dissection book
by Ira Pohl and Charlie McDowell

 



Solution to Homework 4 - Coin Toss
/* CoinTossExample.java
 * Doug Whimore  
*/

import tio.*;

public class CoinTossExample
{
   public static void main(String args[])
   {
      int headsTossed = 0;
      int successCount = 0;
      float probability;

      //get user input
      System.out.println("Welcome to the cointoss example!");
      System.out.print("Please enter the number of trials: ");
      int numberOfTrials = Console.in.readInt();
      System.out.print("Please enter number of coins to toss at each trial: ");
      int numberOfTosses = Console.in.readInt();
      System.out.print("Please enter the number of heads for a success: ");
      int headsForSuccess = Console.in.readInt();

      //do each trial
      for(int i = 0; i < numberOfTrials; i++)
      {
         headsTossed = tossCoins(numberOfTosses);
         if(headsTossed >= headsForSuccess)
            successCount++;
      }
      
      //figure probability
      probability = (float)successCount/(float)numberOfTrials;

      //print the results nice and pretty
      System.out.println("The probabilty of getting " + headsForSuccess + " out of " + numberOfTosses + " tosses is " + probability*100 + "%");
      System.out.println("\n Thanks for playing!");
   }

   public static int tossCoins(int tosses)
   {
      int heads = 0;
      //toss coin tosses times
      for(int i = 0; i < tosses; i++)
      {
         double outcome = Math.random();
         if(outcome > 0.5)
            heads++;
      }
      //return how many heads
      return heads;
   }
}

Feel free to report any site problems to the Webmaster, Debra Dolsberry.