Get random numbers in a specific range in java [duplicate]

孤街醉人 提交于 2020-04-07 18:40:11

问题


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?


回答1:


Random rand = new Random(seed);
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;



回答2:


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




回答3:


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



回答4:


The arg you pass to the constructor is the seed, not the bound.

To get a number between 200 and 500, try the following:

Random random = new Random(); // or new Random(someSeed);
int value = 200 + random.nextInt(300);


来源:https://stackoverflow.com/questions/11743267/get-random-numbers-in-a-specific-range-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!