简体   繁体   中英

Problems generating random numbers within a range with java

I have tried many different ways to generate random numbers but I can't seem to make a simple nextInt(int min, int max) method that will work on negative and positive ranges.

10 to 20 -10 to 10 -10 to -20

If I get it working for one range, the other doesn't work.

What have you tried?

rnd.nextInt(max+1-min)+min;

should work as long as min < max . If you want max exclusive, remove the +1 .

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