Final Exam
Code
/// Name: Kyle Ivy
/// Period: 5
/// Program Name: Final
/// File Name: Final.java
/// Date Finished: 1/20/2016
import java.util.Random;
import java.util.Scanner;
public class Final {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
Random rng = new Random();
int n = 0;
int Heads = 0;
int Tails = 0;
System.out.println("This program will tell you the probablitiy of getting heads or tails from a coin flip." );
System.out.println();
System.out.print("How many times would you like to flip the coin? ");
int Flips = keyboard.nextInt();
do
{
int Flip = rng.nextInt(2);
if ( Flip == 1 )
Heads++;
else
Tails++;
n++;
}
while (n != Flips);
System.out.println();
System.out.println("You got " + Heads + " heads and " + Tails + " tails.");
System.out.println();
double probOfHeads = (double)Heads / Flips;
double probOfTails = (double)Tails / Flips;
System.out.println("The probablitity that you will get heads is " + probOfHeads + " out of 1.0.");
System.out.println("The probablitity that you will get tails is " + probOfTails + " out of 1.0.");
// I used a do while loop because I wanted the loop to be executed at least once. I used the three basic variables number of flips, heads, and tails so that I could find probability. You get a percentage of heads/tails closest to 50% the more times you flip, so I would choose a large number such as 2,000 to get consistently close to 50%.
}
}
Final.PNG