Semester 1 Final

import java.util.Random;
import java.util.Scanner;

public class CoinProbability
{
	public static void main( String[] args )
	{
		Scanner keyboard = new Scanner(System.in);
		Random rng = new Random();
        int target, flips, heads, tails;
        
        System.out.println("This program will flip a coin a given number of times and calculate the probability of getting heads or tails.");
        
        do
        {
            System.out.print("Please enter a number.\n> ");
            target = keyboard.nextInt();
            if (target > 2100000000 || target < 1)
            {
                System.out.println("Invalid number");
            }
        } while (target > 2100000000 || target < 1);

        flips = heads = tails = 0;
        
		while (flips <  target)
		{
			int flip = rng.nextInt(2);
            
            if (flip == 1)
            {
                heads ++;
            }
            else
            {
                tails++;
            }
            flips ++;
		}
        
        if (flips != target || heads + tails != target)
        {
            System.out.println("COUNTING ERROR");
        } // Checks that the target number of flips, the number of flips completed, 
          // and the sum of heads and tails flipped are all equal.
        
        double headsp = (double)heads / flips;
        double tailsp = (double)tails / flips;
        
        System.out.println("Heads flipped: " +heads);
        System.out.println("Tails flipped: " +tails);
        System.out.println("Probability of flipping heads: " +headsp * 100+  "%");
        System.out.println("Probability of flipping tails: " +tailsp * 100+ "%");
	}
}

// The program will consistsntly produce values close to 50% if it flips at least 20000 times.