R_Connor5607
R_Connor5607

Reputation: 57

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

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);
}

Upvotes: 3

Views: 483

Answers (2)

Bohemian
Bohemian

Reputation: 425238

For bonus points in your tutorial, submit this:

public static int rollDie() {
    return DoubleStream.generate(Math::random).limit(n).mapToInt(d -> (int)(d * 6) + 1).sum();
}

Upvotes: 0

janos
janos

Reputation: 124734

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();
}

Upvotes: 2

Related Questions