Assignemnt #Final and Final Exam Coin Flip
Code
///Name: Daniel Tiffany-Appleton
///Period: 7
///Program Name: Final Exam Coin Flip
///File Name: FinalExamCoinFlip
///Date Finished: 1/21/16
import java.util.Random;
import java.util.Scanner;
public class FinalExamCoinFlip
{
public static void main ( String[] args )
{
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
int flips, numberOfHeads, numberOfTails, coinFlips, outcome;// I used flips and coinFlips so the while loops knows to where to stop.
double probablityOfHeads, probabilityOfTails;
System.out.print( "How many times to you want me to flip the coin: ");
flips = keyboard.nextInt();
if( 0 >= flips )//I used ifs here so if a bad number is used then the program will end and state the words in the brackets.
{
System.out.println( "ERROR! Number impossible to use.");
System.out.print( "How many times to you want me to flip the coin: ");
flips = keyboard.nextInt();
}
else if(flips > 2100000000)
{
System.out.println( "ERROR! Number impossible to use.");
System.out.print( "How many times to you want me to flip the coin: ");
flips = keyboard.nextInt();
}
numberOfHeads = 0;
numberOfTails = 0;
coinFlips = 0;
while(coinFlips != flips) //I used a while loop so flips and the outcomes can be checked before the coin is flipped.
{
outcome = r.nextInt(2);
if( outcome == 0 )
{
numberOfHeads++;
}
else if( outcome == 1 )
{
numberOfTails++;
}
coinFlips++;
}
probablityOfHeads = (double)numberOfHeads / flips;
probabilityOfTails = (double)numberOfTails / flips;
System.out.println(" ");
System.out.println( "Number of Heads: " + numberOfHeads + ". Probability of landing on Heads: " + probablityOfHeads + ".");
System.out.println(" ");
System.out.println( "Number of Tails: " + numberOfTails + ". Probability of landing on Heads: " + probabilityOfTails + ".");
System.out.println(" ");
}
}
//The best number 21000000 because it is the highest number that the computer can use and this number will get to the closest 50/50 because it will even out and little variations will not show up.
Picture of the output