Little_Berry
Little_Berry

Reputation: 23

Dice Statistics Program

I'm trying to write a java program that asks the user to enter in the amount of dice to roll and the amount of times to roll the dice.

The program that I wrote so far isn't rolling the dice properly: if I roll 2 dice, then 2 and 24 should have the least amount of rolls and the middle numbers would have the most amount of rolls. Right now it rolls each number pretty evenly.

Does anyone know how I can fix this?

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

public class DiceStats {
    public static Random rand= new Random();

    public static int rollDice() {
        int dice;
        dice=(rand.nextInt(6)+1);   
        return dice;               // returns the sum dice rolls
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("How many dice will constitute one roll? ");
        int diceNumber = input.nextInt();

        System.out.print("How many rolls? ");
        int rollNumber = input.nextInt();

        int[] frequency = new int[6*diceNumber+1];

        for (int i = 0; i < rollNumber; i++) {
            ++frequency[(rollDice()*diceNumber)];
        }

        System.out.printf("%s%10s\n", "Face", "Frequency");

        for (int face= diceNumber; face <frequency.length; face++)
            System.out.printf("%4d%10d\n", face, frequency[face]);
    }
}

Upvotes: 0

Views: 1606

Answers (1)

Kevin W.
Kevin W.

Reputation: 1183

Your problem (at least the one in the question) is right in the line

++frequency[(rollDice()*diceNumber)];

Instead of rolling n dice and summing them, you're rolling 1 die and multiplying it by n. You would want to have something like

int sum = 0;
for(int i = 0;i<diceNumber;i++)
    sum+=rollDice();
++frequency[sum];

That will more accurately simulate dice, as you have individual dice rolls for each die.

Upvotes: 4

Related Questions