Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 259
imulsion Avatar asked Jul 31 '12 15:07

imulsion


People also ask

How do you get a random double within a range in Java?

In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

How do you generate a random number from 1 to 6 in Java?

For example, in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random.


2 Answers

Random rand = new Random(seed);
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;
like image 143
CosmicComputer Avatar answered Oct 01 '22 03:10

CosmicComputer


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

like image 38
pcalcao Avatar answered Oct 01 '22 03:10

pcalcao