Assignment = Semester 1 Final
Code
/// Name: Sam Wilson
/// Period: 6
/// Program Name: final1
/// File Name: final1.java
/// Date Finished: 1/22/16
import java.util.Random;
import java.util.Scanner;
public class final1
{
public static void main(String[] args)
{
Random s = new Random();
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello please choose the amount of flips you want between 1-2,100,000,000");
System.out.print("> ");
while (!keyboard.hasNextInt()) //Did research this prevents String codes
{
keyboard.next();
System.out.println("Please enter a valid Input");
System.out.print("> ");
}
int flips = keyboard.nextInt();
System.out.println();
while (flips > 2100000000 && 0 > flips)
{
System.out.println("Please enter a valid Integer that falls within the provided range.");
System.out.print("> ");
flips = keyboard.nextInt();
}
int n = 0;
int h = 0;
int t = 0;
int rand;
do
{
rand = 1 + s.nextInt(2); //used the basic .5 prob and a count to do the computer toss.
if (rand == 1)
{
h++;
n++;
}
else if (rand == 2)
{
t++;
n++;
}
}
while (flips != n);
double probH = (double)h / flips;
double probT = (double)t / flips;
double perH = probH * 100;
// Wanted to prevent any errors in this process so split into two
double perT = probT * 100;
System.out.println();
System.out.println("You rolled "+h+" heads and "+t+" tails.");
System.out.println("Probability of Rolling Heads: "+perH+"%");
System.out.println("Probability of Rolling Tails: "+perT+"%");
}
}
Picture of the output