Get random numbers in a specific range in java
Possible Duplicate:
Java: generating random number in a range
I want to generate random numbers using
java.util.Random(arg);
The only problem is, the method can only take one argument, so the number is always between 0 and my argument. Is there a way to generate random numbers between (say) 200 and 500?
Random rand = new Random(seed);
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;
First of, you have to create a Random object, such as:
Random r = new Random();
And then, if you want an int value, you should use nextInt
int myValue = r.nextInt(max);
Now, if you want that in an interval, simply do:
int myValue = r.nextInt(max-offset)+offset;
In your case:
int myValue = r.nextInt(300)+200;
You should check out the docs:
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
I think you misunderstand how Random works. It doesn't return an integer, it returns a Random object with the argument being the seed value for the PRNG.
Random rnd = new Random(seed);
int myRandomValue = 200 + rnd.nextInt(300);
链接地址: http://www.djcxy.com/p/17664.html
上一篇: 如何生成一个随机的五位数字Java
下一篇: 在java中获取特定范围内的随机数