Okay. First, try to only create the Random
instance once, but for an example,
int rand = -15 + new Random().nextInt(31);
is the range -15 to 15.
The Random.nextInt(int)
JavaDoc says (in part) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive). Note that your provided example of (30 - 20) + 1
is the range 0 to 10 (inclusive).
As a further example, to get the range 20 to 30 you would use:
int rand = 20 + new Random().nextInt(11);
Remember, the bounds of the result of is 0 to n
.
30 - -10. I'm trying to make a survival simulator. That will be my temperature.
Ok. Let's write that range as -10
to 30
. nextInt(n)
will return a value between 0
and n
, so if you want the range below 0 you must subtract 10
from the result and add 10
to the n
. That's
Random random = new Random();
int rand = random.nextInt(41) - 10;
Now let's examine how we can determine those numbers. Remember, nextInt()
will return between 0
and n
(exclusive) and we want -10
to 30
(inclusive); so 41
is n
and we subtract 10
. If the result is 0
(the min) we get -10
, if the result is 40
(the max) we get 30
.