Assignment Final Exam Program
Code
/// Name: Matthew Lorence
/// Period: 5
/// Program Name: Coin Flip Final
/// File Name: CoinFlipFinal.java
import java.util.Scanner;
import java.util.Random;
public class CoinFlipFinal
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
int flips, outcome, addflips, heads, tails;
addflips = 0; //Used to add up total number of flips until it is equal to the flips the user wanted.
heads = 0; // Start off with 0 heads flipped.
tails = 0; // Start off with 0 tails flipped.
System.out.println("How many times do you want to flip the coin? (Pick from 1 to 2.1 billion)");
flips = keyboard.nextInt();
while (addflips != flips) // Use while to keep flipping the coin until the number of flips is equal to the number of flips the user wanted.
{
outcome = r.nextInt(2);
if (outcome==0) // Adds to the total number of tails if the if statement is true.
{
tails++;
}
else if (outcome==1) //Adds to the total number of heads if the else if statement is true.
{
heads++;
}
addflips++; // Adds up total of flips done through random number generator.
}
System.out.println("Tails: " + tails);
System.out.println("Heads: " + heads);
double probtails = (double)tails / flips;
System.out.println("Probability of tails: " + probtails);
double probheads = (double)heads / flips;
System.out.println("Probability of heads: " + probheads);
// The consistent number of flips needed to get to as close to 50% chance for heads or tails is infinity, but in the case of an interger which maxes out 2,100,000,000, 2,100,000,000
would be the number needed to get as close to 50% chance as possible for heads and tails.
}
}
Picture of the output