简体   繁体   中英

Is it possible to generate random negative number range in Java?

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);

只需生成10到20之间的随机数,然后取反即可。

另一个选择是生成一个0到10之间的随机数,然后减去20(如果您觉得这不太像解决方法)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM