First Semester Final Exam

Code

    ///Name: Cody Swain
    ///Period: 6
    ///Project Name: Final
    ///File Name: Final.java
    ///Date: 1/22/16
    
    import java.util.Random;
    import java.util.Scanner;
    
    public class Final
    {
        public static void main( String[] args ) 
        {
            Scanner keyboard = new Scanner(System.in);
            Random r = new Random();
            int x, heads, tails, flips;
            heads = 0;
            tails = 0;
            flips = 0;
            
            while ( flips <= 0 ){       //use a while loop to ask them for a correct number, and keep asking if they input an incorrect number.
                System.out.println( "Enter the number of times to flip a coin: ");
                flips = keyboard.nextInt();
                if (flips <= 0 ){
                    System.out.print( "Error, re-enter a proper number. " );
                }
            }
            
            for ( x = 0; x < flips; x++ ){ //for loop is the easiest way to make sure the coin flip function occurs the amount of times the user inputs.
                int y = 1 + r.nextInt(2); //generates either a 1 or 2
                if ( y == 1 ){
                    heads++;            //adds 1 to existing value of "heads" if number generated is a 1.
                }
                else if ( y == 2 ){     //adds 1 to existing value of "tails if the number generated is 2.
                    tails++;
                }
            }
            
            double probHeads = (double)heads / flips;
            double probTails = (double)tails / flips;
            
            System.out.println( "Heads: " + heads );
            System.out.println( "Tails: " + tails );
            System.out.println( "Probability of rolling heads in this case was: " + probHeads*100 + "%" );
            System.out.println( "Probability of rolling tails in this case was: " + probTails*100 + "%" );
        }
    }
            
    
    /* 
    To get as close as possible to 50%, it is optimal to flip the coin as many times as possible. So within the range of an interval, 1000000000 or 1x10^9 is a consistent number to get as close to 50% as possible.
    */
    
    
    

                
                
        
    

Picture of the output

Final