Assignemnt Final Exam Program
Code
///Name: Prooz Fereydouni
///Period: 7
///Project Name: Final Exam Program
///File Name: SOF.java
///Date: 1/21/2016
import java.util.Random;
import java.util.Scanner;
public class SOF
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
Random rng = new Random();
int heads=0, tails=0, NumberFlips, FlipCount=0; // introducing heads, tails and FlipCount because they will not be initialized at the beginning which is not the case for NumberFlips as it will be initialized by user.
String coin;
System.out.println("How many times do you want me to flip a coin? The number should be greater than or equal to 1 and less than or equal to 2,100,000,000");
NumberFlips = keyboard.nextInt();
while(NumberFlips < 1 || NumberFlips > 2100000000) //used while because we do not want the program to run even once if the number givent isnt int the logical range
{
System.out.println("Wrong input. The number should be greater than or equal to 1 and less than or equal to 2,100,000,000");
NumberFlips = keyboard.nextInt();
}
do //used do while becease we want the program to run and run until the we reach the number given by the user to terminate the process of flipping
{
int flip = rng.nextInt(2);// probability intiger which will later be translated into heads and tails
if ( flip == 1 )
{
heads = heads + 1;
coin = "heads"; // a string that is going to tell us about the outcome after every flip
}
else
{
tails = tails + 1;
coin = "tails";
}
System.out.println( "You flip a coin and it is... " + coin );
FlipCount = FlipCount + 1; // increases the flip count until it reaches the number of flips given
}while ( NumberFlips != FlipCount );// terminates the loop until it reaches the number of flips given
System.out.println( "Number of heads were: " + heads);
System.out.println( "Number of tails were: " + tails);
double probOfHeads = ((double)heads / NumberFlips) * 100; //used double for probabilities because it can have decimal.
double probOfTails = ((double)tails / NumberFlips) * 100;
System.out.println( "The proability of flipping another heads is: " + probOfHeads);
System.out.println( "The proability of flipping another tails is: " + probOfTails);
//The higher the number of flips is the closer to 50 the probability is. Here is the result of some of the trials.
//01: 100%, 0%
//02: 100%, 0%
//10: 60%, 40%;
//90000: 50.03%, 40.97%
}
}
Picture of the output