How do I generate a random int value in a specific range?I have tried the following, but those do not work:Attempt 1:randomNum = minimum + (int)(Math.random() * maximum);// Bug: `randomNum` can be bigger than `maximum`.Attempt 2:Random rn = new Random();int n = maximum - minimum + 1;int i = rn.nextInt() % n;randomNum =minimum + i;// Bug: `randomNum` can be smaller than `minimum`.

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?

**2019年08月19日11分44秒**

This doesn't work for longs

**2019年08月19日11分44秒**

MoisheLipsker It must be that nextLong doesn't take a bound as nextInteger

**2019年08月19日11分44秒**

leventov ThreadLocalRandom was added to Java 2 1/2 years after this question was first asked.I've always been of the firm opinion that management of the Random instance is outside the scope of the question.

**2019年08月19日11分44秒**

In Android Random rand = new Random();

**2019年08月19日11分44秒**

The Sun documentation explicitly says that you should better use Random() if you need an int instead of Math.random() which produces a double.

**2019年08月19日11分44秒**

This is actually biased compared to nextInt methods stackoverflow.com/a/738651/360211

**2019年08月19日11分44秒**

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

**2019年08月19日11分44秒**

if you may, can you explain what is the significance of streamSize - the first param of this method given streamSize !=0. What is the difference if streamSize 1/2/n is given?

**2019年08月20日11分44秒**

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

**2019年08月19日11分44秒**

+1 for wayBackMachine archive screenshot link & your answer is still useful reference to get "random" ints w/in a range.

**2019年08月19日11分44秒**

It baffles me why you instantiate index to 0.

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

Exactly... it's completely unused. I would initialise it directly to the rand: int index = rand.nextInt(i.Length);

**2019年08月19日11分44秒**

Why not throw an IllegalArgumentException when the difference = Integer.MAX_VALUE? Then you don't need the while loop.

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

// 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.

**1970年01月01日00分07秒**

MaartenBodewes +1 is added because getRandomNumberBetween generates a random number exclusive of the provided endpoints.

**2019年08月19日11分44秒**

The number min + 1 will be twice as likely than the other number to be the result of getRandomNumberBetween!

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

Double.valueOf(Math.random()*(maximum-minimun)).intValue() is quite an obfuscated (and inefficient) way to say (int)(Math.random()*(maximum-minimun))…

**2019年08月19日11分44秒**

Spelling mismatch for minimumreturn minimum + Double.valueOf(Math.random() * (maximum - minimum)).intValue();

**2019年08月19日11分44秒**

I don't see anything new here that hadn't been posted in countless earlier posts.

**2019年08月19日11分44秒**

Dupe of another answer

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

You need seed, yes, but using SecureRandom.

**2019年08月19日11分44秒**

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.

**1970年01月01日00分03秒**

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: }

**2019年08月19日11分44秒**

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.

**2019年08月19日11分44秒**

- Getting random numbers in Java
- How can I generate random number in specific range in Android?
- Java Generate Random Number Between Two Given Values
- Generating a Random Number between 1 and 10 Java
- Java random number with given length
- How to generate random positive and negative numbers in Java
- Get random integer in range (x, y]?
- Specify max and min for Random.nextInt()?
- Get random numbers in a specific range in java
- How to generate a random five digit number Java
- How to generate a random alpha-numeric string?
- How do I efficiently iterate over each entry in a Java Map?
- How do I read / convert an InputStream into a String in Java?
- Generate random string/characters in JavaScript
- Generating random whole numbers in JavaScript in a specific range?
- How do I generate a random int number?
- Generate random integers between 0 and 9
- Generate random number between two numbers in JavaScript
- How do I convert a String to an int in Java?
- Getting random numbers in Java

ADS