简体   繁体   English

使用Java生成范围内的随机数时出现问题

[英]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. 我尝试了许多不同的方法来生成随机数,但是我似乎无法制作一个简单的nextInt(int min,int max)方法,该方法可以在负范围和正范围内工作。

10 to 20 -10 to 10 -10 to -20 10至20 -10至10 -10至-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 . 只要min < max都应该工作。 If you want max exclusive, remove the +1 . 如果要最大独占,请删除+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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