Fall Final

Code

//jack newsom
//period 5
//program FallFinal
//filename FallFinal.java

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

public class FallFinal
{
    public static void main( String[] args ) {

        
       Scanner input = new Scanner(System.in);
        
        System.out.println("Hello. This program will tell you how many heads and tails you get from a certain number of coin flips and the probability of each outcome.");
        
        System.out.println("Please select a number of coin flips (between 1 and 2,100,000,000).");
        int flipNum = input.nextInt();
        
        
        //while loop allows program to run repeatedly until the number of flips completed is equal to the number of flips the user requested
        while ( flipNum < 1 || flipNum > 2100000000 )
        {
            System.out.println("Whoops! Your number was ");
            
            if ( flipNum < 1 )
            {
                System.out.print("too small.");
            }
            else
            {
                System.out.print("too large.");
            }
            
            System.out.println("Please select a number between 1 and 2,100,000,000.");
            flipNum = input.nextInt();
        }
        
        Random r = new Random();
        
        int flipsCompleted = 0;
        int headTotal = 0;
        int outcome = 0;
        
        while ( flipsCompleted < flipNum )
        {
                outcome = r.nextInt(2); //picks a number between 0 and 1. 0 is tails and 1 is heads. 
                
                headTotal = headTotal + outcome; //adds all heads together
            
                flipsCompleted++; //increases number of flips completed so while loop doesn't run infinitely.
                
        }
        
        
        int tailTotal = flipsCompleted - headTotal;
        
        
        System.out.println("In " + flipNum + " coin flips, " + headTotal + " heads were rolled and " + tailTotal + " tails were rolled.");
        
        double headProbability = (double)headTotal / flipsCompleted; //gives probability of rolling a head
        double tailProbability = (double)tailTotal / flipsCompleted; //gives probability of rolling a tail
        
        System.out.println("In this specific trial, the probability of rolling a head was " + headProbability + ".");
        System.out.println("The probability of rolling a tail was " + tailProbability + ".");
                           
        
        
        
      //for the program to consistently give a 50% chance to heads and to tails, the number of flips would need to be infinity. Because we cannot tell the computer to flip the coin infinity times, we are limited to the maximum value an integer can hold, 2.1 billion.
    }
}
    

Picture of the output

Fall Final Picture