Final Exam: Coin Flip w/ Probability
Code
/// Name: Cassie
/// Period: 6
/// Program Name: Final Exam
/// File Name: finalExam.java
/// Date Finished: 1/22/2016
import java.util.Random;
import java.util.Scanner;
class finalExam
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
Random rng = new Random();
int flipAmount;
int tries = 0, heads = 0, tails = 0;
System.out.println( "Pick an amount of times to flip the coin" );
System.out.println( "(No less than one no greater than 2,100,000,000)" );
System.out.print( " > " );
flipAmount = keyboard.nextInt();
if ( flipAmount > 2100000000 )
{
System.out.println( "That number does not follow the guidelines" );
System.out.println( "Select a new number that is no less than one no greater than 2,100,000,000" );
System.out.print( " > " );
flipAmount = keyboard.nextInt();
}
if ( flipAmount < 1 )
{
System.out.println( "That number does not follow the guidelines" );
System.out.println( "Select a new number that is no less than one no greater than 2,100,000,000" );
System.out.print( " > " );
flipAmount = keyboard.nextInt();
}
do
{
int flip = rng.nextInt(2);
tries ++;
if ( flip == 1 )
heads++;
else
tails++;
} while ( tries < flipAmount);
System.out.println( "You rolled " + heads + " heads and " + tails + " tails." );
double probabilityOfHeads = heads++ / flipAmount;
double probOfHeads = (((double)heads++) / flipAmount) * 100;
System.out.println( "Your probability of rolling heads is " + probOfHeads );
}
}
Picture of the output