Semester 1 Final
Code
/// Name: Ryan McAteer
/// Period: 5
/// Program Name: Semester 1 Final
/// File Name: Final.java
/// Date Finished: 1/20/16
import java.util.Scanner;
import java.util.Random;
public class Final
{
public static void main ( String[] args )
{
Scanner keyboard = new Scanner(System.in); //This is quite a challenging subject for me so I played it safe//
Random rng = new Random();
int numberOfTimes, steps, heads, tails; //Logical variables for the assignment//
steps = 0;
heads = 0;
tails = 0;
System.out.println("Hello! Welcome to my final! How many times should I flip the coin?");
System.out.print("> ");
numberOfTimes = keyboard.nextInt();
do //Assignment 70 was a good base for this assignment as it involves coins, do while loops, and the rng elements
{
int flip = rng.nextInt(2);
if ( flip == 1 )
{
heads++;
steps++; //<- for the "numberOfTimes" variable//
}
else
{
tails++;
steps++;
}
} while ( steps != numberOfTimes ); // I felt a do-while loop made this assignment easier//
System.out.println("You flipped " + heads + " heads and " + tails + " tails.");
int numberOfHeads, numberOfTails, chances; //Probability syntax required for last bit of the assignment//
numberOfHeads = 50;
chances = 100;
double probOfHeads = (double)numberOfHeads / chances;
numberOfTails = 50;
double probOfTails = (double)numberOfTails / chances;
System.out.println("You had a " + probOfHeads + "% chance of rolling heads and a " + probOfTails + "% chance of rolling tails.");
//I started by using the number 10 for numberOfTimes just to test my program. After I had it working, I changed 10 to 100 This number was the closest I could get to a 50/50 chance as after running 10 trials, heads "won" 5 and tails "won" 5. I tried 1000 for numberOfTimes, but the variance only increased. While 100 was the number, the difference was no more than 5 for my ten trials, but when 1000 was the number, the difference was always 20+ for the 10 trials.//
}
}
Picture of the output