Final Exam 1 and Final Exam Program
Code
import java.util.Random;
import java.util.Scanner;
public class FinalExam1
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
Random rng = new Random();
int heads = 0;
int tails = 0;
int flips = 0;
String coin;
System.out.println( "How many times do you want to flip your coin? Make sure it is between 1 and 2,100,000,000" );
int totalTries = keyboard.nextInt();
//This while is for when the input is less than or greater than 21000000000 and it will ask for a new input between 1 and 2100000000.
//If you input 2111111111111111111 the program wont run but if you put 2100000002 it is too high and will ask for an input.
while ( totalTries < 1 || totalTries > 2100000000 )
{
System.out.println( "Make sure the number is between 1 and 2,100,000,000" );
totalTries = keyboard.nextInt();
}
//do-while because it initializes the number of flips inside then does the while based on the number of flips
do
{
int flip = rng.nextInt(2);
if ( flip == 1 )
{
heads++;
}
if ( flip == 0 )
{
tails++;
}
flips++;
//There are two variables flip and flips the flip is for the rng and flips counts the number of flips for probability
} while ( flips < totalTries);
double probOfHeads = (double)heads / flips;
double probOfTails = (double)tails / flips;
System.out.println("Out of " + flips + " flips " + heads + " came up heads and " + tails + " came up tails.");
System.out.println("Probability of heads: " + probOfHeads );
System.out.println("Probability of tails: " + probOfTails );
//A good number to input that leads to a 50 50 most of the time is 200 if the number that is inputed is too big the probability would be 49.9999 and 50.0001
//or something very close and if it is too small the probability could be 100 and 0 if you only do 2 flips but close to 50 50 with a chance of exactly 50/50
//I found to be 200.
}
}
Picture of the output