Thursday, September 12, 2013

Flow Chart and Code: Coin Toss


I would like for you to create the following:

Part 1: Random Coin Toss
  • Create a Class called CoinToss
  • Add appropriate comments, titles and attributions
  • Display a title "text graphic" when the program is executed
  • Generate a random number (using either of the methods that I showed you)
  • Display whether the result was a Heads or a Tails
 Part 2: Count Results
  • Loop for 1000 "flips"
  • Count the number of Heads
  • Count the number of Tails
  • Display the total number of Heads and Tails
 Part 3: Coin Toss Guess
  • Ask the user if they want heads or tails (maybe a 1 or a 2) right now
  • Randomly select Heads or Tails
  • Tell the user whether they win or lose
  • Optional: Count wins & losses and loop until user quits (i.e. enters a 0)
This is an example code using some techniques you haven't learned yet.  I am sharing this so you can see how simple you can make the code.  Also notice that I added comments to the end } tags.  This helps me remember where things should be.

//import statements
import java.util.*;
 
public class FlipCoin
{
    public static void main(String [] args)
    {
        //declare variables
       double flip;
        int count = 0;
        int countHeads = 0;
        int countTails = 0;         
         
        //Loop
        for(int x = 0; x <= 10;x = x++)
        {
            x = x + 1;
           //flip
           flip = Math.random();
            //if statement
           if( flip <= .5)
            {  
                flip = countHeads;
                countHeads = countHeads + 1;
                }
            else
            {          
                flip = countTails;
              countTails = countTails + 1;            
            }
            
            count = count +1;             
                     
        }//End Loop         
         
}//End Main
}//End Class

No comments:

Post a Comment