Final Exam
Code
/// Name: Xinting Chen
/// Period: 7
/// Program Name: Final Exam
/// File Name: FinalExam.java
/// Date Finished: 1/21/2016
import java.util.Scanner;
import java.util.Random;
import java.util.InputMismatchException;
public class FinalExam
{
public static void main( String[] args )
{
Random r = new Random();
int heads = 0;
int tails = 0;
int flips = getFlips();
for (int i = 0; i< flips; i++)
{
if (r.nextInt(2)==0)
tails++;
else
heads++;
}
double probHeads = ((double)heads / flips *100);
double probTails = ((double)tails / flips *100);
System.out.println( "The number of heads is ... " + heads);
System.out.println( "The number of tails is ... " + tails);
System.out.println( "The probablity of rolling heads is... " + probHeads + "%");
System.out.println( "The probablity of rolling tails is... " + probTails + "%");
}
static int getFlips()
{
Scanner keyboard = new Scanner(System.in);
boolean exception = false;
int flips = 0;
while (flips <= 0 || flips >= 2100000000)
{
keyboard = new Scanner(System.in);
exception= false;
try
{
System.out.println( "How many times do you want to flip the coin? " );
flips = keyboard.nextInt();
}
catch (InputMismatchException e)
{
System.out.println( "Try another number please.");
flips = 0;
exception = true;
}
if (( flips <=0 || flips >= 2100000000) && !exception)
System.out.println( "Try another number that's greater than 0 and less than 2100000000.");
}
return flips;
}
}
Picture of the output