Get random numbers in a specific range in java

Possible duplicate:
Java: generating a random number in a range

I want to generate random numbers using

java.util.Random(arg); 

The only problem is that 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?

+6
source share
4 answers
 Random rand = new Random(seed); int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound; 
+24
source

First you must create a Random object, for example:

 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 in between just do:

  int myValue = r.nextInt(max-offset)+offset; 

In your case:

  int myValue = r.nextInt(300)+200; 

You should check the documents:

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

+5
source

I think you misunderstand how Random works. It does not return an integer, it returns a Random object with an argument that is the initial value for PRNG.

 Random rnd = new Random(seed); int myRandomValue = 200 + rnd.nextInt(300); 
+3
source

The argu you pass to the constructor is a seed, not a border.

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); 
+1
source

Source: https://habr.com/ru/post/921775/


All Articles