# Random int in range [solved]

Discussion in 'Spigot Plugin Development' started by blohod, Jul 12, 2015.

1. ### blohod

I want to make the int XCoord be random between min and max, however I can not figure out how to make it work.

Code (Text):
Random randomNo = new Random();
int XCoord = randomNo.nextInt(min-max);
This is very wrong, how do I do it right?

Also it needs to work with negative numbers

to clarify I am trying to choose a coordinate between min and max, and as in minecraft coordinates can be positive or negative

#1
Last edited: Jul 12, 2015
2. Random#nextInt(int n) generates a random value from 0 to n-1. If you want it to be negative, just multiply by negative 1. Also, this value should be assigned to the int primative type, not the Integer wrapper class.

3. ### blohod

not quite what I want as I want the number i get to bet between min and max, and min and/or max can be negative, as this is generating a minecraft coordinate

I am also not sure if I am anywhere near right with my code, so if there is a better way to get random numbers then that is what i want.

4. ### BetaNyan

Code (Text):
int max = 5000;
int min = max * 2;

Random r = new Random();

int randomNum = r.nextInt(max) - min;
This might work, I am very tired and on my phone, so it could be wrong.

6. ### blohod

I don't think this allows me to set the minimum separately to the maximum

7. ### BetaNyan

Oh I thought you wanted something like -5000 to 5000

8. ### blohod

sorry, I want it to be anything to anything

eg. -3455 to 4556
434565 to 34543454532
-34 to -4

9. ### BetaNyan

Try

Code (Text):
int rand = random.nextInt(max - min) + min;

10. The first answer will work fine. You can literally use that exact method and it'll work fine for you 11. ### blohod

don't think that works

12. ### blohod

ok, i will try and figure it out from that

13. ### BetaNyan

It's actually what Grunt posted I believe..

14. ### blohod

Code (Text):
int min = -20;
int max = 60;
int XCoord = randomNo.nextInt((max-min) + 1) + min;

so this will generate a random number between -20 and 60?

15. ### blohod

sorry, i think my brain is imploding now

16. Test it and find out 17. ### MeRPG

I Guarentee you that works... I use a line of code breat exactly like it all the time

• Like x 1
18. ### blohod

I think it does, could you please explain how it works to me as my brain is refusing to work

19. Of course Code (Text):
int min = -20;
int max = 60;
int XCoord = randomNo.nextInt((max-min) + 1) + min;

When you do (max-min) + 1 you are saying to generate a random value between 0 and the difference between the max and min values minus 1 because nextInt() generates from 0 to n-1, which is why you add 1, so the values in your range won't be 1 less than what you specified. Then, you add the minimum value to the random number to actually get a value in the range you specified. Let me know if that makes sense at all, as I'm pretty tired and it's really early in the morning • Informative x 2