24

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?

Community
  • 1
  • 1
imulsion
  • 8,820
  • 20
  • 54
  • 84
  • 1
    How unclear can it be? You have an upper bound. You want that to be offset by a number. Add that number. Using `+`. Like, say, `x + 200`. – Dave Newton Jul 31 '12 at 15:14
  • Did you notice that when you create question SO shows you list of possible similar questions, for example [this one](http://stackoverflow.com/questions/363681/java-generating-random-number-in-a-range?rq=1) so you can find answers quicker? – Pshemo Jul 31 '12 at 15:15

4 Answers4

50
Random rand = new Random(seed);
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;
algorowara
  • 1,700
  • 1
  • 15
  • 15
6

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

pcalcao
  • 15,789
  • 1
  • 44
  • 64
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);
ymgve
  • 318
  • 2
  • 7
1

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);
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92