0

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]);
 }
}
nobody
20.3k17 gold badges59 silver badges80 bronze badges
asked Jul 3, 2014 at 19:46
2
  • 4
    Right now you're only rolling one die per roll, and multiplying that value by diceNumber. You need to actually roll diceNumber times (i.e. with another loop). Commented Jul 3, 2014 at 19:53
  • There is no method called in main. Commented Jul 3, 2014 at 19:57

1 Answer 1

4

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.

answered Jul 3, 2014 at 19:57
Sign up to request clarification or add additional context in comments.

1 Comment

I made the change, I replaced n ++frequency[(rollDice()*diceNumber)]; with int sum = 0; for(int i = 0;i<diceNumber;i++) sum+=rollDice(); ++frequency[sum]; but now its printing out all 0s and one 1, what's going on now?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.