Cornelius Eanes's Programming Portal
Assignments (Final Exam 1)
Display Probability

Goal: Flip a coin a certain number of times, and calculate the resulting probabilities from how many times heads and tails were rolled.

/// Name: Cornelius Eanes
/// Period: 5
/// Program Name: (Final Exam 1) Display Probability
/// File Name: DisplayProbability.java
/// Date Finished: Jan 20, 2016

import java.util.Random;
import java.util.Scanner;

public class DisplayProbability {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        int flips, heads = 0, tails = 0;

        System.out.print("Choose how many times you want to flip a coin: ");
        do {
          flips = input.nextInt();
          if (flips <= 0) {
            System.out.println("Please enter a number higher than 0.");
          }
        } while (flips <= 0);
        // I assign a new variable specifically for the loop.
        // I want to keep the original value for the results display.
        int i = flips;
        // Instead of decreasing i at the end of the loop, I decrease it
        // after its comparison so there's less code cluttering up the file.
        while (i-- > 0) {
            /* If the boolean is true, then we call it heads, otherwise, tails
            I used Random#nextBoolean() as opposed to nextInt(2) because
            otherwise, I would have to assign a variable, and check to see what
            it's equal to. With my approach, it's both simple to read and quick to run. */
            if (rand.nextBoolean()) {
                heads++;
            } else {
                tails++;
            }
        }

        System.out.println("Number of flips: " + flips);
        // Casting one of the values to a double forces the output to become a double
        double headsProbability = (double) heads / flips;
        double tailsProbability = (double) tails / flips;
        System.out.println("Number of heads: " + heads);
        System.out.println("Number of tails: " + tails);
        System.out.println("Probability of heads: " + headsProbability);
        System.out.println("Probability of tails: " + tailsProbability);

        /*

        The more flips are made, the closer to 0.5 and 0.5 we get for the probabilities.
        So, the maximum integer value (2^31 - 1) will yield the most accurate results.

         */

    }

}

Output