Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to count the sum of n dice (without using arrays)

Tags:

java

loops

I'm trying to develop a method that interacts with this main class code to find the sum of n dice. (the main class program limits this count to the sum of 2, 3, 4 and 5 dice respectively).

for (int numberOfDice = 2; numberOfDice <= 5; ++numberOfDice) {
        System.out.println("Rolling " + numberOfDice + " dice gives "
                + MathCalc.rollDice(numberOfDice));

The task of the method is to sum the number of dice (each evaluation is independent of another, meaning that the sum of 3 dice could be 11 for example while the sum of 4 dice might only be 8.) using only a loop and some local variables.

I have produced this method for another section of my code to simulate a single roll of the dice but for some reason I cant seem to wrap my head around this next step.

public static int rollDie() {
    //roll a random number between 1-6 to simulate the roll of a die 
    return 1 + (int) (Math.random() * 6);
}
like image 400
R_Connor5607 Avatar asked Dec 13 '25 07:12

R_Connor5607


1 Answers

Math.random is obsolete and flawed, don't use it, use Random instead, specifically its nextInt() method, for example:

Random random = new Random();

// get values in the range [1:6]
int roll() {
    return 1 + random.nextInt(6);
}

To sum up n rolls, call this method in a loop:

int sum = 0;
for (int numberOfDice = 0; numberOfDice < count; ++numberOfDice) {
    sum += roll();
}
like image 83
janos Avatar answered Dec 15 '25 21:12

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!