Generating random numbers within an interval

I've been trying to find the easiest way to write to generate a number which is between intervals of a arbitrary min and a max value.

I've been searching for this but I don't find this particular thing.

I've found that this combination works:

Code:

`int guess = rand.nextInt(max - (min - 1)) + min;`

But I wonder, is this really the easiest way of writing it?

Re: Generating random numbers within an interval

Your code may be wrong, but that depends exactly how you are defining min and max. If both ends of the range are inclusive, then you've written it correctly. As always, you can split up complex statements into multiple lines:

Code:

`int range = max - min + 1; // omit +1 if max is exclusive`

int guess = min + rand.nextInt(range);

Re: Generating random numbers within an interval

Maybe I'm wrong and this isn't doable this way, but I'm pretty sure that if you read up on

That there is a way to do it. I seem to recall doing

Code:

`int random = (int) math.random() * 45 + 10;`

or something like that to get a random number between 10 and 55?

Re: Generating random numbers within an interval

Quote:

Originally Posted by

**kjkrum** Your code may be wrong, but that depends exactly how you are defining min and max. If both ends of the range are inclusive, then you've written it correctly. As always, you can split up complex statements into multiple lines:

Code:

`int range = max - min + 1; // omit +1 if max is exclusive`

int guess = min + rand.nextInt(range);

Yes both ends of the range should be inclusive. Thanks for clarifying.

Just to clarify, does this work also for negative numbers? It seems it does when I try but I want to make sure.

Re: Generating random numbers within an interval

It should. But it would not work if min > max.

Re: Generating random numbers within an interval