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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With