TK11612 - 2 years ago 66
Java Question

# Creating a Dice Roller in Java. Help me understand why this works?

I stopped programming a few years ago because I didn't think I would get to graduate. Surprise, now I am, and I have to brush up on rusty novice skills. I decided to start with a dice rolling program written in Java. The first version of this program is just supposed to spit out a random number between 1 and 10. As I go I plan to expand it with a GUI that allows the user to select the number and type of dice to roll.

The first version of this program works. My problem is that I don't know why it works. I was first going to use java.util.random and use random.nextInt() but the range was enormous and I couldn't figure out how to limit it to a specific range.

I searched online and found something that worked. Here's what I have.

``````class DiceRoller {

public static void main(String[] arguments){

int min = 1;
int max;
int result;

result = rollDice(10, min);

System.out.println(result);
}

public static int rollDice(int maximum, int minimum){
return ((int) (Math.random()*(maximum - minimum))) + minimum;
}
}
``````

The specific part that I found to make this work is:

``````    public static int rollDice(int maximum, int minimum){
return ((int) (Math.random()*(maximum - minimum))) + minimum;
}
``````

But I don't understand why it works. Is it something with random() within the Math class itself that differs from Random in java.util? Why is it necessary to take the random number and multiply it by the difference of the maximum and minimum, then add that result to the minimum? To be honest I feel stupid for asking but I want to understand why this works rather than just take the code and use it because it does.

`Math.random()` returns a random number between 0 and 1.