25

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?

2
  • 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. Commented Jul 31, 2012 at 15:14
  • Did you notice that when you create question SO shows you list of possible similar questions, for example this one so you can find answers quicker? Commented Jul 31, 2012 at 15:15

4 Answers 4

51
Random rand = new Random(seed);
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;
Sign up to request clarification or add additional context in comments.

5 Comments

Great thanks! It works fine, and your answer was by far the most constructive and useful to me :)
@imulsion Modulo it being wrong, of course; there's no Random constructor that returns a random number. All three other answers use the class correctly, in addition to giving an example of addition.
Besides being wrong, there's nothing wrong with it.
I just used nextInt() instead; it was still the most constructive answer
int next = random.nextInt(upper - lower + 1) + lower;
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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.