HIDE NAV

Basic Dice Simulator

The below command line program is a sample soluiton to Code Assignment 6 - Dice Statistics. Note this does not include any optional optional extras.

DiceSim.java


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

public class Main {
    public static void main(String[] args) {
        int numRolls;
        int[] rollCounts = new int[13];
        double[] rollProbs = new double[13];

        //Intro/Greeting
        System.out.println("Dice Roll Sim.");
        //Ask how many times to roll -> n
        System.out.println("how many times to roll a pair of 6 sided dice?");
        Scanner inScan = new Scanner(System.in);
        numRolls = inScan.nextInt();

        //run a loop 'n' times
        int loopCount = 0;
        while(loopCount < numRolls) {
            int sum = rollDie() + rollDie();
            rollCounts[sum]++;
            loopCount++;
        }

        //Report counts of roll outcomes
        int i = 2;
        while(i < rollCounts.length){
            System.out.println("Number of " + i + "'s rolled = " + rollCounts[i]);
            i++;
        }

        //calc. a %age from roll counts
        i = 2;
        while(i < rollProbs.length){
            double p = rollCounts[i] / (double)numRolls;
            rollProbs[i] = p;
            i++;
        }
        
        //print out roll chance as percentage
        i = 2;
        while(i < rollProbs.length) {
            double percent = rollProbs[i] * 100;
            System.out.println("Probability of rolling a " + i + " = " + percent + "%");
            i++;
        }

    }

    //A method to generate 1-6 with equal probability 
    //  i.e. simulate a single roll of a 6 sided die
    static int rollDie(){
        Random randGen = new Random();
        int r = randGen.nextInt(6); // note: this generates [0,5]
        r = r + 1; // shift to [1,6]
        return r;
    }

}