TK11612 - 1 year ago 36

Java Question

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.

Answer

`Math.random()`

returns a random number between 0 and 1.

So if you want a random number between 0 and n instead, you just have to multiply by n.

Now if you want a number between m and n, you will want to do what is done there : multiply by n - m, then add m.

Example with a roll between 2 and 5 :

- I've got my random number between 0 and 1
- I multiply it by 5 - 2 = 3. Now I've got a random number between 0 and 3
- I add 2. Now I've got a random number between 2 and 5

Source (Stackoverflow)