Reputation: 841
I have seen MANY posts on here in regard to generating random numbers with a specific range in JAVA (especially this one). However, I have not found one that describes how to generate a random number between a negative MAX and a negative MIN. Is this possible in Java?
For example, if I want to generate a random number that is between (-20) and (-10). Using something like the below will only result in a JAVA Exception that screams about n having to be positive:
int magicNumber=(random.nextInt(-20)-10);
Upvotes: 0
Views: 2001
Reputation: 3863
I'm not entirely sure what you want, but ThreadLocalRandom
has a method which accepts a range, which can also have negative values:
ThreadLocalRandom.current().nextInt(-20, -10 + 1)
There is no practical difference to just negating the result of a positive random though.
Upvotes: 2
Reputation: 2309
Another option would be to generate a random number between 0 and 10 and then subtract 20, if that feels less like a work-around to you.
Upvotes: 2