-2

I don't know why Java's designers didn't design java.util.Random objects to return random numbers like this:

rand.nextInt(minValue, maxValue);

I don't understand how to pass min and max values to this function. I've seen this recommended:

random.nextInt(max + 1 - (min)) + min

but what does that mean? Does that mean:

random.nextInt(FULL_RANGE + 1) + START_OF_RANGE

For example, if I wanted to generate values between -1 and 1, inclusive, is this how I do it:

int oneOfThreeChoices = rand.nextInt(1 + 1 + 1) - 1;

Code_Steel
  • 437
  • 2
  • 8
  • 14
  • Regarding "what does that mean": `max - min + 1` is the size of the range. E.g., if you want values in the range `[1, 4]` then you want 4 different values (1, 2, 3, 4) -- that's `4 - 1 + 1`. Now, since the arg to nextInt is exclusive, you want to pass in 4. This gets you values in {0, 1, 2, 3}, so whatever value from that you get, you just shift it up 1 (ie, `min`) to get values in {1, 2, 3, 4}. – yshavit Aug 25 '16 at 19:34
  • The answer that is linked by the mods is a much more complicated question. The top answer is irrelevant. How is that helpful? It doesn't help me. – Code_Steel Aug 25 '16 at 19:48
  • How is it irrelevant? As far as I can tell, your question is basically "how do I generate a random int in a given min/max range?" If that's your question, the linked duplicate answers it, and my comment here even explains it a bit by example. If that's not your question, what is? – yshavit Aug 25 '16 at 20:30

2 Answers2

3

The API provides sufficient tools for you to complete this task. If you want an random int on the range [a,b], inclusive on both ends, use

int n = random.nextInt(b-a+1) + a

assuming that random is an object previously declared to be of type java.util.Random.

Brick
  • 3,998
  • 8
  • 27
  • 47
2

random.nextInt(bound) returns random number from 0 to bound (exclusive). For example random.nextInt(10) returns random number from 0 to 9.

So, if you want to return number from 5 to 15 (inclusive) just say

random.nextInt(11) + 5

Why java designers have not included more convenient API to JDK? I think because the way explained here is pretty simple and obvious.

AlexR
  • 114,158
  • 16
  • 130
  • 208