Semester 1 Final!
Code
/// Name: Dylan Sleeper
/// Period: 6
/// Program Name: Flip Probability
/// File Name: flipProbability.java
/// Date Finished: 1/22/2016
import java.util.Scanner;
import java.util.Random;
public class flipProbability{
public static void main(String[] args){
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
double tailsCount = 0;
double headsCount = 0;
int userInput;
int times = 0;
System.out.println("How many times would you like to flip the coin?");
do{
userInput = 0;
if(times > 0){
System.out.println("Not a valid number. Please enter another number.");
}
System.out.print("> ");
String temp = keyboard.next();
// The try and catch to make sure the number is a valid integer that isn't a string, double, or too big. This
// prevents the program from crashing.
try{
userInput = Integer.parseInt(temp);
}
catch(java.lang.NumberFormatException e){
userInput = -1;
}
times++;
System.out.println("");
// This checks to make sure the number isn't negative or 0 because that would throw errors later in the
// program.
} while(userInput <= 0);
for(int i = 0; i < userInput; i++){
int flip = r.nextInt(2);
if(flip == 0){
tailsCount++;
}
else{
headsCount++;
}
}
double total = userInput;
double tailsPercent = (tailsCount / total) * 100;
double headsPercent = (headsCount / total) * 100;
System.out.println("Heads: " + headsPercent + "%");
System.out.println("Tails: " + tailsPercent + "%");
System.out.println("");
System.out.println("You rolled " + headsCount + " heads and " + tailsCount + " tails.");
}
}
/*
I found that using about 8000 gets consistently close to 50% every time.
*/
Outputs