4130

How do I generate a random int value in a specific range?

The following methods have bugs related to integer overflow:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
Mahozad
26.2k19 gold badges163 silver badges198 bronze badges
asked Dec 12, 2008 at 18:20
2
  • 47
    Before you post a new answer, consider there are already 65+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers. Commented Feb 3, 2020 at 11:53
  • Use ThreadLocalRandom.current().nextInt(min, max + 1); in Java to get random integers in a range. This method is simple, reliable, and often used in games like pvzfusionapk.pro. Commented Sep 25 at 10:19

59 Answers 59

1
2
4399
+150

Java 7+

In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows:

import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.

Java 17+

As of Java 17, the psuedorandom number generating classes in the standard library implement the RandomGenerator interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, the SecureRandom class can be used.

Earlier Java

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random;
/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value. Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {
 // NOTE: This will (intentionally) not run as written so that folks
 // copy-pasting have to think about how to initialize their
 // Random instance. Initialization of the Random instance is outside
 // the main scope of the question, but some decent options are to have
 // a field that is initialized once and then re-used as needed or to
 // use ThreadLocalRandom (if using at least Java 1.7).
 // 
 // In particular, do NOT do 'Random rand = new Random()' here or you
 // will get not very good / not very random results.
 Random rand;
 // nextInt is normally exclusive of the top value,
 // so add 1 to make it inclusive
 int randomNum = rand.nextInt((max - min) + 1) + min;
 return randomNum;
}

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

Basil Bourque
346k128 gold badges947 silver badges1.3k bronze badges
answered Dec 12, 2008 at 18:25
Sign up to request clarification or add additional context in comments.

5 Comments

For calls where max value is Integer.MAX_VALUE it is possible to overflow ,resulting into a java.lang.IllegalArgumentException. You can try with : randInt(0, Integer.MAX_VALUE). Also, if nextInt((max-min) + 1) returns the most high value (quite rare, I assume) won't it overflow again( supposing min and max are high enough values)? How to deal with this kind of situations?
Now there is nextLong​(long origin, long bound) available. Posting for reference. I am unaware of the fact if it was there when asnwer for posted.
I prefer ThreadLocalRandom solution even if you can't specify the seed or you don't need a thread safe method, since the API is more intuitive if min != 0.
I would argue that this is no longer the "standard answer" as of Java 17, though it works well if you want a single global multhreaded generator. Per RandomGenerator, "It is recommended that multithreaded applications use either ThreadLocalRandom or (preferably) pseudorandom number generators that implement the RandomGenerator.SplittableGenerator or RandomGenerator.JumpableGenerator interface." See: stackoverflow.com/a/70529176/1108305.
@user42155 Remember to mark an answer as correct if it was!
1519

Note that this approach is more biased and less efficient than a nextInt approach, https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

Min + (int)(Math.random() * ((Max - Min) + 1))

The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

For example, if you want [5,10), you need to cover five integer values so you use

Math.random() * 5

This would return a value in the range [0,5), where 5 is not included.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

Min + (Math.random() * (Max - Min))

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

5 + (Math.random() * (10 - 5))

But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

Min + (int)(Math.random() * ((Max - Min) + 1))

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))
Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Dec 12, 2008 at 18:35

5 Comments

The Sun documentation explicitly says that you should better use Random() if you need an int instead of Math.random() which produces a double.
This is actually biased compared to nextInt methods stackoverflow.com/a/738651/360211
"Biased" in this case means that after 2^53 executions, some numbers will have had one extra occourance, on average.
Even thought i use this too, i want to point out that this is not a true random number. Thats why it should not be used for any security functionality. But for any casual cases it is the most straight forwrd method.
Also, the nextInt() methods in Random do not include the upper bound.
469

Use:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

The integer x is now the random number that has a possible outcome of 5-10.

Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Sep 4, 2009 at 4:23

Comments

206

Use:

minValue + rn.nextInt(maxValue - minValue + 1)
learner
1311 silver badge12 bronze badges
answered Dec 12, 2008 at 18:25

Comments

202

With Java 8 they introduced the method ints(int randomNumberOrigin, int randomNumberBound) in the Random class.

For example if you want to generate five random integers (or a single one) in the range [0, 10], just do:

Random r = new Random();
int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray();
int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();

The first parameter indicates just the size of the IntStream generated (which is the overloaded method of the one that produces an unlimited IntStream).

If you need to do multiple separate calls, you can create an infinite primitive iterator from the stream:

public final class IntRandomNumberGenerator {
 private PrimitiveIterator.OfInt randomIterator;
 /**
 * Initialize a new random number generator that generates
 * random numbers in the range [min, max]
 * @param min - the min value (inclusive)
 * @param max - the max value (inclusive)
 */
 public IntRandomNumberGenerator(int min, int max) {
 randomIterator = new Random().ints(min, max + 1).iterator();
 }
 /**
 * Returns a random number in the range (min, max)
 * @return a random number in the range (min, max)
 */
 public int nextInt() {
 return randomIterator.nextInt();
 }
}

You can also do it for double and long values.

M. Justin
23k12 gold badges133 silver badges167 bronze badges
answered Nov 26, 2014 at 18:29

1 Comment

I would suggest that you instantiate the randomIterator only once. See Greg Case comment on his own answer.
125

You can edit your second code example to:

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum = rn.nextInt(range) + minimum;
answered Dec 12, 2008 at 18:31

Comments

110

Just a small modification of your first solution would suffice.

Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

See more here for implementation of Random

Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Mar 12, 2015 at 22:44

1 Comment

For minimum <= value < maximum, I did the same with Math : randomNum = minimum + (int)(Math.random() * (maximum-minimum)); but the casting isn't really nice to see ;)
102

ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.

int rand = ThreadLocalRandom.current().nextInt(x,y);

x,y - intervals e.g. (1,10)

Ihor Patsian
1,2982 gold badges17 silver badges27 bronze badges
answered Feb 12, 2013 at 23:19

Comments

80

The Math.Random class in Java is 0-based. So, if you write something like this:

Random rand = new Random();
int x = rand.nextInt(10);

x will be between 0-9 inclusive.

So, given the following array of 25 items, the code to generate a random number between 0 (the base of the array) and array.length would be:

String[] i = new String[25];
Random rand = new Random();
int index = 0;
index = rand.nextInt( i.length );

Since i.length will return 25, the nextInt( i.length ) will return a number between the range of 0-24. The other option is going with Math.Random which works in the same way.

index = (int) Math.floor(Math.random() * i.length);

For a better understanding, check out forum post Random Intervals (archive.org) .

Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Jan 8, 2009 at 15:04

4 Comments

It baffles me why you instantiate index to 0.
@CodeConfident The index variable will not affect the result of the random number. You can choose to initialize it any way you would like without having to worry about changing the outcome. Hope this helps.
Exactly... it's completely unused. I would initialise it directly to the rand: int index = rand.nextInt(i.Length);
Or not at all. int index; \n index = rand... if one is fond of declarations and assignments on different lines. Some coding standards are more stringent (and without apparent purpose) than others.
64

It can be done by simply doing the statement:

Randomizer.generate(0, 10); // Minimum of zero and maximum of ten

Below is its source code.

File Randomizer.java

public class Randomizer {
 public static int generate(int min, int max) {
 return min + (int)(Math.random() * ((max - min) + 1));
 }
}

It is just clean and simple.

Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answered Sep 1, 2013 at 2:53

7 Comments

This could have been an edit of the other example, now it is just a blatant copy for reputation. Pointing out the "answer with the most votes" is also not very direct, it can change.
That is right @MaartenBodewes. When I wrote this answer, the answer with the most votes above was still written as an algorithm-like solution. Now, the solution above has changed a lot and now this answer looked like a copy-cat.
I really don't get why such fundamental bits of code are not part of Java standard libraries. Why do I have to implement this?
@MaartenBodewes When two answers provide the same solution, and both have been edited, it may not be clear and obvious which answer provided a given solution first. In that scenario please be very cautious about accusing anyone of "blatant copy for reputation". (I'm all in favor of calling out copycats, but just make sure that you don't make a false accusation, which is what seems to have happened here.)
@skomisa What the hell are you talking about, it explicitly pointed towards the answer with the same solution and then wrote a function header in front of it.
|
54

Forgive me for being fastidious, but the solution suggested by the majority, i.e., min + rng.nextInt(max - min + 1)), seems perilous due to the fact that:

  • rng.nextInt(n) cannot reach Integer.MAX_VALUE.
  • (max - min) may cause overflow when min is negative.

A foolproof solution would return correct results for any min <= max within [Integer.MIN_VALUE, Integer.MAX_VALUE]. Consider the following naive implementation:

int nextIntInRange(int min, int max, Random rng) {
 if (min > max) {
 throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
 }
 int diff = max - min;
 if (diff >= 0 && diff != Integer.MAX_VALUE) {
 return (min + rng.nextInt(diff + 1));
 }
 int i;
 do {
 i = rng.nextInt();
 } while (i < min || i > max);
 return i;
}

Although inefficient, note that the probability of success in the while loop will always be 50% or higher.

Azeem
15k4 gold badges36 silver badges53 bronze badges
answered Jan 10, 2011 at 13:19

2 Comments

Why not throw an IllegalArgumentException when the difference = Integer.MAX_VALUE? Then you don't need the while loop.
@mpkorstanje This implementation is designed to work with any values of min <= max, even when their difference is equal to or even larger than MAX_VALUE. Running a loop until success is a common pattern in this case, to guarantee uniform distribution (if the underlying source of randomness is uniform). Random.nextInt(int) does it internally when the argument is not a power of 2.
37

I wonder if any of the random number generating methods provided by an Apache Commons Math library would fit the bill.

For example: RandomDataGenerator.nextInt or RandomDataGenerator.nextLong

beat
1,8821 gold badge24 silver badges41 bronze badges
answered Dec 12, 2008 at 18:27

Comments

35

As of Java 7, you should no longer use Random. For most uses, the random number generator of choice is now ThreadLocalRandom.

For fork join pools and parallel streams, use SplittableRandom.

Joshua Bloch. Effective Java. Third Edition.

Starting from Java 8

For fork join pools and parallel streams, use SplittableRandom (it implements SplittableGenerator interface, see Java 17 notes below) that is usually faster, has a better statistical independence and uniformity properties in comparison with Random.

To generate a random int in the range [0, 1_000]:

int n = new SplittableRandom().nextInt(0, 1_001);

To generate a random int[100] array of values in the range [0, 1_000]:

int[] a = new SplittableRandom().ints(100, 0, 1_001).parallel().toArray();

To return a Stream of random values:

IntStream stream = new SplittableRandom().ints(100, 0, 1_001);

Java 17

It is recommended that multithreaded applications use either ThreadLocalRandom or (preferably) pseudorandom number generators that implement the RandomGenerator.SplittableGenerator or RandomGenerator.JumpableGenerator interface.

RandomGenerator 1 documentation.


1 - RandomGenerator is a modern interface that was introduced in Java 17. It is a common protocol for objects that generate random or pseudorandom sequences of numbers and has more features and methods than Random.

answered Apr 11, 2018 at 21:54

2 Comments

Is there a reason why the example includes a .parallel()? It seems to me like generating a 100 random numbers would be too trivial to warrant parallelism.
@Johnbot Thanks for comment, you are right. But, the main reason was to show an API (of course, the smart path is to measure performance before using parallel processing). By the way, for array of 1_000_000 elements, the parallel version was 2 times faster on my machine in comparison with sequential.
34

I use this:

 /**
 * @param min - The minimum.
 * @param max - The maximum.
 * @return A random double between these numbers (inclusive the minimum and maximum).
 */
 public static double getRandom(double min, double max) {
 return (Math.random() * (max + 1 - min)) + min;
 }

You can cast it to an Integer if you want.

answered May 28, 2017 at 14:30

3 Comments

This function produces the same number over and over again. In my case it was: 2147483647
Fail: you have a function that requires a double and then perform + 1? This certainly goes against the principle of least surprise. What happens if you use min = 0.1 and max = 0.2?
@sokras the method calls new Random (check the JavaDoc): "Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor." Very likely might just involve using the current time as seed. If that time uses milliseconds then current computers are fast enough to generate the same number. But besides that 2147483647 is Integer.MAX_VALUE; the output obviously depends on the input, which you haven't specified.
32
 rand.nextInt((max+1) - min) + min;
Youcef LAIDANI
60.2k21 gold badges110 silver badges177 bronze badges
answered Dec 12, 2008 at 18:25

Comments

31

Let us take an example.

Suppose I wish to generate a number between 5-10:

int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);

Let us understand this...

Initialize max with highest value and min with the lowest value.

Now, we need to determine how many possible values can be obtained. For this example, it would be:

5, 6, 7, 8, 9, 10

So, count of this would be max - min + 1.

i.e. 10 - 5 + 1 = 6

The random number will generate a number between 0-5.

i.e. 0, 1, 2, 3, 4, 5

Adding the min value to the random number would produce:

5, 6, 7, 8, 9, 10

Hence we obtain the desired range.

Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Aug 3, 2014 at 3:07

Comments

29

Generate a random number for the difference of min and max by using the nextint(n) method and then add min number to the result:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);
Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered May 27, 2015 at 10:43

1 Comment

How is this different from previous answers?
21

In case of rolling a dice it would be random number between 1 to 6 (not 0 to 6), so:

face = 1 + randomNumbers.nextInt(6);
GAMITG
3,8187 gold badges35 silver badges51 bronze badges
answered Feb 16, 2010 at 8:50

Comments

21

To generate a random number "in between two numbers", use the following code:

Random r = new Random();
int lowerBound = 1;
int upperBound = 11;
int result = r.nextInt(upperBound-lowerBound) + lowerBound;

This gives you a random number in between 1 (inclusive) and 11 (exclusive), so initialize the upperBound value by adding 1. For example, if you want to generate random number between 1 to 10 then initialize the upperBound number with 11 instead of 10.

Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Nov 2, 2017 at 6:38

Comments

21
int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();

Or take a look to RandomUtils from Apache Commons.

Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Dec 12, 2008 at 18:28

3 Comments

That's useful, but beware a small flaw: method signatures are like: nextDouble(double startInclusive, double endInclusive), but if you look inside the methods, endInclusive should actually be endExclusive.
Double.valueOf(Math.random()*(maximum-minimun)).intValue() is quite an obfuscated (and inefficient) way to say (int)(Math.random()*(maximum-minimun))...
Spelling mismatch for minimum return minimum + Double.valueOf(Math.random() * (maximum - minimum)).intValue();
21

Just use the Random class:

Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Dec 24, 2013 at 13:33

3 Comments

I don't see anything new here that hadn't been posted in countless earlier posts.
@MaartenBodewes Those countless posts are hard to find. Some other methods on top
Yeah, posting yet another dupe is not going to help against that. Vote up the other answers or add details. Otherwise it is just rep farming.
21

These methods might be convenient to use:

This method will return a random number between the provided minimum and maximum value:

public static int getRandomNumberBetween(int min, int max) {
 Random foo = new Random();
 int randomNumber = foo.nextInt(max - min) + min;
 if (randomNumber == min) {
 // Since the random number is between the min and max values, simply add 1
 return min + 1;
 } else {
 return randomNumber;
 }
}

and this method will return a random number from the provided minimum and maximum value (so the generated number could also be the minimum or maximum number):

public static int getRandomNumberFrom(int min, int max) {
 Random foo = new Random();
 int randomNumber = foo.nextInt((max + 1) - min) + min;
 return randomNumber;
}
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answered Aug 12, 2012 at 15:01

3 Comments

// Since the random number is between the min and max values, simply add 1. Why? Doesn't min count? Usually the range is [min, max) where min is included and max is excluded. Wrong answer, voted down.
@MaartenBodewes +1 is added because getRandomNumberBetween generates a random number exclusive of the provided endpoints.
The number min + 1 will be twice as likely than the other number to be the result of getRandomNumberBetween!
19

Here's a helpful class to generate random ints in a range with any combination of inclusive/exclusive bounds:

import java.util.Random;
public class RandomRange extends Random {
 public int nextIncInc(int min, int max) {
 return nextInt(max - min + 1) + min;
 }
 public int nextExcInc(int min, int max) {
 return nextInt(max - min) + 1 + min;
 }
 public int nextExcExc(int min, int max) {
 return nextInt(max - min - 1) + 1 + min;
 }
 public int nextIncExc(int min, int max) {
 return nextInt(max - min) + min;
 }
}
answered Feb 15, 2012 at 16:19

Comments

19

Another option is just using Apache Commons:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;
public void method() {
 RandomData randomData = new RandomDataImpl();
 int number = randomData.nextInt(5, 10);
 // ...
 }
Azeem
15k4 gold badges36 silver badges53 bronze badges
answered Jan 18, 2012 at 16:15

Comments

19

You can achieve that concisely in Java 8:

Random random = new Random();
int max = 10;
int min = 5;
int totalNumber = 10;
IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);
Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Jun 20, 2017 at 12:39

Comments

18

I found this example Generate random numbers :


This example generates random integers in a specific range.

import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
 public static final void main(String... aArgs){
 log("Generating random integers in the range 1..10.");
 int START = 1;
 int END = 10;
 Random random = new Random();
 for (int idx = 1; idx <= 10; ++idx){
 showRandomInteger(START, END, random);
 }
 log("Done.");
 }
 private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
 if ( aStart > aEnd ) {
 throw new IllegalArgumentException("Start cannot exceed End.");
 }
 //get the range, casting to long to avoid overflow problems
 long range = (long)aEnd - (long)aStart + 1;
 // compute a fraction of the range, 0 <= frac < range
 long fraction = (long)(range * aRandom.nextDouble());
 int randomNumber = (int)(fraction + aStart); 
 log("Generated : " + randomNumber);
 }
 private static void log(String aMessage){
 System.out.println(aMessage);
 }
} 

An example run of this class :

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Jun 7, 2012 at 10:38

Comments

18
public static Random RANDOM = new Random(System.nanoTime());
public static final float random(final float pMin, final float pMax) {
 return pMin + RANDOM.nextFloat() * (pMax - pMin);
}
Martijn Pieters
1.1m325 gold badges4.2k silver badges3.4k bronze badges
answered Jul 13, 2011 at 11:31

Comments

17

RandomGenerator in Java 17+

// Random int between minimum (inclusive) & maximum (exclusive)
int randomNum = RandomGenerator.getDefault().nextInt(minimum, maximum);

The int nextInt(int origin, int bound) method was added in Java 17 as part of the RandomGenerator interface. It generates a random integer in a given range.

This interface is used for new random generation algorithms added in Java 17:

RandomGenerator.getDefault().nextInt(minimum, maximum);
RandomGenerator.of("L128X1024MixRandom").nextInt(minimum, maximum);
RandomGenerator.of("Xoroshiro128PlusPlus").nextInt(minimum, maximum);
// ...

The RandomGenerator interface was also added to the existing random generation classes (Random, SecureRandom, SplittableRandom, and ThreadLocalRandom). Therefore, as of Java 17, those four classes also have this bounded nextInt method:

new Random().nextInt(minimum, maximum);
new SecureRandom().nextInt(minimum, maximum);
new SplittableRandom().nextInt(minimum, maximum);
new ThreadLocalRandom().nextInt(minimum, maximum);

This method is new to Random and SecureRandom as of Java 17. Prior to Java 17, ThreadLocalRandom and SplittableRandom already had this method, though it was not specified by a shared interface.

More info

answered Dec 30, 2021 at 8:30

3 Comments

Be aware that there is a bug in RandomGenerator.getDefault().nextInt(int, int) in Java 17 causing it to return the same number every time. For example RandomGenerator.getDefault().nextInt(0, 10) always return 2. It is fixed in version 19 as far as I know.
@BjørnStenfeldt Good to be aware of. I'm not sure if that's a "bug" per se since those aren't subsequent requests to the same RandomGenerator so there's no requirement that two created RandomGenerator instances be distinguishable from each other. It's also not the first time in Java that creating the Random class each time lead to this sort of behavior. I remember Random behaving the same way back in the day when the starting seed was based solely on the millisecond timestamp of when it was created. They did add a "seed uniquifier" back in Java 5 or something to prevent that.
@BjørnStenfeldt To follow up on my comment from last year for anybody new reading these, a solution would be to reuse the same RandomGenerator, being careful not to violate the thread safety requirements.RandomGenerator random = RandomGenerator.getDefault(); int int1 = random.nextInt(0, 10); int int2 = random.nextInt(0, 10);
15

Here is a simple sample that shows how to generate random number from closed [min, max] range, while min <= max is true

You can reuse it as field in hole class, also having all Random.class methods in one place

Results example:

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

Sources:

import junit.framework.Assert;
import java.util.Random;
public class RandomUtils extends Random {
 /**
 * @param min generated value. Can't be > then max
 * @param max generated value
 * @return values in closed range [min, max].
 */
 public int nextInt(int min, int max) {
 Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
 if (min == max) {
 return max;
 }
 return nextInt(max - min + 1) + min;
 }
}
answered Nov 28, 2014 at 0:50

Comments

15

It's better to use SecureRandom rather than just Random.

public static int generateRandomInteger(int min, int max) {
 SecureRandom rand = new SecureRandom();
 rand.setSeed(new Date().getTime());
 int randomNum = rand.nextInt((max - min) + 1) + min;
 return randomNum;
}
Peter Mortensen
31.5k22 gold badges110 silver badges134 bronze badges
answered Mar 26, 2015 at 13:02

8 Comments

This is not that good, because if it is executed in the same mili second then you will get the same number, you need to put the rand initialization and the setSeet outside of the method.
You need seed, yes, but using SecureRandom.
I'm sorry, but the one who rejected the change request has no clue of Java programming It is a good suggestion, but as is it is wrong because if executed in the same mili second it will give the same number, not random.
The correct solution isn't anywhere to be found, not many people know static initializer blocks... that is what you should use to set the seed: 1: private static int SecureRandom rand = new SecureRandom(); 2: static { 3: rand.setSeed(...); 4: }
There is absolutely no need to seed SecureRandom, it will be seeded by the system. Directly calling setSeed is very dangerous, it may replace the (really random) seed with the date. And that will certainly not result in a SecureRandom, as anybody can guess the time and try and seed their own SecureRandom instance with that information.
|
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.