4073

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
  • 18,032
  • 13
  • 118
  • 133
user42155
  • 48,965
  • 27
  • 59
  • 60
  • 41
    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. – janniks Feb 03 '20 at 11:53
  • When you need a lot of random numbers, I do not recommend the Random class in the API. It has just a too small period. Try the [Mersenne twister](http://en.wikipedia.org/wiki/Mersenne_twister) instead. There is [a Java implementation](http://cs.gmu.edu/~sean/research/). – raupach Dec 13 '08 at 10:18
  • The corresponding one for JavaScript: *[Generating random whole numbers in JavaScript in a specific range](https://stackoverflow.com/questions/1527803/)* – Peter Mortensen Oct 04 '22 at 16:17

73 Answers73

4342

In Java 1.7 or later, the standard way to do this 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 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. In those situations, the pre-Java 1.7 technique shown below can be used.

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.

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
Greg Case
  • 46,881
  • 3
  • 27
  • 21
  • 48
    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? – Daniel Aug 12 '14 at 10:34
  • 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. – Jabir Apr 05 '22 at 10:52
  • 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`. – Marco Sulla May 20 '23 at 13:19
1506

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,048,767
  • 296
  • 4,058
  • 3,343
TJ_Fischer
  • 15,881
  • 2
  • 23
  • 20
  • 87
    The Sun documentation explicitly says that you should better use Random() if you need an int instead of Math.random() which produces a double. – Lilian A. Moraru Feb 23 '12 at 23:26
  • 7
    This is actually biased compared to nextInt methods http://stackoverflow.com/a/738651/360211 – weston Dec 29 '16 at 13:35
  • 8
    "Biased" in this case means that after 2^53 executions, some numbers will have had one extra occourance, on average. – Cephalopod Aug 29 '19 at 09:48
  • 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. – Tobias Oct 20 '20 at 13:28
  • Also, the nextInt() methods in Random do not include the upper bound. – Nils Reiter Nov 29 '22 at 12:58
454

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,048,767
  • 296
  • 4,058
  • 3,343
203

Use:

minValue + rn.nextInt(maxValue - minValue + 1)
learner
  • 111
  • 9
krosenvold
  • 75,535
  • 32
  • 152
  • 208
194

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

starball
  • 20,030
  • 7
  • 43
  • 238
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • 3
    I would suggest that you instantiate the randomIterator only once. See Greg Case comment on his own answer. – Naxos84 Feb 26 '18 at 07:13
122

You can edit your second code example to:

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
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,048,767
  • 296
  • 4,058
  • 3,343
hexabunny
  • 1,405
  • 1
  • 11
  • 12
  • 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 ;) – AxelH Jul 08 '16 at 12:30
100

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,288
  • 2
  • 15
  • 25
andrew
  • 3,083
  • 4
  • 24
  • 29
78

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,048,767
  • 296
  • 4,058
  • 3,343
Matt R
  • 2,577
  • 5
  • 30
  • 46
  • It baffles me why you instantiate index to 0. – charles-allen Aug 02 '17 at 13:53
  • @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. – Matt R Aug 02 '17 at 14:38
  • Exactly... it's completely unused. I would initialise it directly to the rand: `int index = rand.nextInt(i.Length);` – charles-allen Aug 02 '17 at 14:41
  • 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. – Mark Storer Sep 17 '19 at 18:24
63

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
  • 30,738
  • 21
  • 105
  • 131
Abel Callejo
  • 13,779
  • 10
  • 69
  • 84
  • 6
    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. – Maarten Bodewes Jun 19 '17 at 21:23
  • 2
    That is right @MaartenBodewes. When I wrote this answer, [the answer with the most votes above](https://stackoverflow.com/revisions/363692/15) 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. – Abel Callejo Jun 20 '17 at 00:36
  • 2
    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? – Leevi L Oct 08 '19 at 08:31
  • @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 Feb 03 '23 at 23:48
  • @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. – Maarten Bodewes Feb 04 '23 at 06:28
  • @MaartenBodewes I can't view deleted comments, but I can see the current comments, and also the revision history of answers. You have accused the person who posted this answer of creating _"a blatant copy for reputation"_. However, at the time this answer was posted it was (and still is) using a different algorithm to generate a random number compared to the linked answer (`Math.random()` vs. `Random.nextInt()`). So apart from other considerations, your accusation is baseless and false. Since you falsely smeared this poster publicly, it would be classy for you to now offer a public apology. – skomisa Feb 04 '23 at 20:59
  • Well, thank you, I'll take your comments into consideration, comparing it to " If you want to try the answer with the most votes above, you can simply use this code:" which is *literally* the initial answer. – Maarten Bodewes Feb 04 '23 at 21:40
53

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
  • 11,148
  • 4
  • 27
  • 40
Joel Sjöstrand
  • 655
  • 5
  • 4
  • Why not throw an IllegalArgumentException when the difference = Integer.MAX_VALUE? Then you don't need the while loop. – M.P. Korstanje Jan 09 '15 at 10:27
  • 3
    @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. – Christian Semrau May 06 '15 at 19:27
35

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,857
  • 1
  • 22
  • 36
Chinnery
  • 10,179
  • 2
  • 23
  • 25
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.

Simon
  • 2,686
  • 2
  • 31
  • 43
  • This function produces the same number over and over again. In my case it was: 2147483647 – sokras Jul 20 '17 at 07:38
  • 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? – Maarten Bodewes Apr 23 '18 at 21:26
  • @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. – Maarten Bodewes Apr 23 '18 at 21:36
33

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 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);
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
  • 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 Jul 20 '18 at 06:29
  • @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. – Oleksandr Pyrohov Jul 20 '18 at 08:35
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,048,767
  • 296
  • 4,058
  • 3,343
Sunil Chawla
  • 351
  • 3
  • 6
31
 rand.nextInt((max+1) - min) + min;
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
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,048,767
  • 296
  • 4,058
  • 3,343
gifpif
  • 4,507
  • 4
  • 31
  • 45
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
  • 30,738
  • 21
  • 105
  • 131
Luke Taylor
  • 9,481
  • 13
  • 41
  • 73
  • `// 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. – Maarten Bodewes Mar 01 '17 at 21:26
  • @MaartenBodewes +1 is added because getRandomNumberBetween generates a random number exclusive of the provided endpoints. – Luke Taylor Mar 02 '17 at 09:53
  • 2
    The number `min + 1` will be twice as likely than the other number to be the result of `getRandomNumberBetween`! – Lii Jun 17 '18 at 12:21
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,048,767
  • 296
  • 4,058
  • 3,343
Prof Mo
  • 483
  • 5
  • 9
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,048,767
  • 296
  • 4,058
  • 3,343
Lawakush Kurmi
  • 2,726
  • 1
  • 16
  • 29
20

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,810
  • 7
  • 32
  • 51
sam
  • 217
  • 2
  • 2
20
int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();

Or take a look to RandomUtils from Apache Commons.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2427
  • 7,842
  • 19
  • 61
  • 71
  • 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. – zakmck Jan 30 '15 at 09:27
  • `Double.valueOf(Math.random()*(maximum-minimun)).intValue()` is quite an obfuscated (and inefficient) way to say `(int)(Math.random()*(maximum-minimun))`… – Holger Jun 03 '16 at 09:47
  • 1
    Spelling mismatch for minimum return minimum + Double.valueOf(Math.random() * (maximum - minimum)).intValue(); – Hrishikesh Mishra Dec 26 '16 at 05:14
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,048,767
  • 296
  • 4,058
  • 3,343
18

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
  • 11,148
  • 4
  • 27
  • 40
gerardw
  • 5,822
  • 46
  • 39
18

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;
    }
}
Garrett Hall
  • 29,524
  • 10
  • 61
  • 76
17

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,048,767
  • 296
  • 4,058
  • 3,343
Hospes
  • 419
  • 4
  • 10
17
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,048,767
  • 296
  • 4,058
  • 3,343
AZ_
  • 21,688
  • 25
  • 143
  • 191
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;
    }
}
Yakiv Mospan
  • 8,174
  • 3
  • 31
  • 35
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
  • 30,738
  • 21
  • 105
  • 131
grep
  • 5,465
  • 12
  • 60
  • 112
  • 1
    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. – maraca Apr 16 '15 at 19:30
  • You need seed, yes, but using SecureRandom. – grep Apr 17 '15 at 12:03
  • 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. – maraca Apr 18 '15 at 09:19
  • 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: `}` – maraca Apr 18 '15 at 09:30
  • the int on line one should be deleted in my example. And the two first lines inside of your function. The rest stays the same. – maraca Apr 18 '15 at 09:39
  • 7
    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. – Maarten Bodewes Mar 01 '17 at 21:32
  • @MaartenBodewes Note that the docs for `SecureRandom.setSeed` say that "The given seed supplements, rather than replaces, the existing seed." hence this idiom seems safe, if somewhat pointless. I've seen this wording used back to Java 1.1, but https://docs.oracle.com/javase/6/docs/api/java/security/SecureRandom.html#setSeed(long) are the oldest docs from Oracle I can find. That said, I agree that seeding seems like cargo-cult programming – you'll get a lot more entropy from the system's pool than from the current time – Sam Mason Jul 19 '22 at 08:24
  • Unfortunately the actual implementation did not always do this if you reseeded before using it. Of course, the method name is also asinine. It should have been called "reseed" to confirm with terminology or even the more direct `supplementSeed`. I'll have to investigate what different Java versions do with this and beware that Android implementations have been - uh - somewhat dysfunctional in the past. – Maarten Bodewes Jul 19 '22 at 10:13
13
rand.nextInt((max+1) - min) + min;

This is working fine.

GAMITG
  • 3,810
  • 7
  • 32
  • 51
ganesh
  • 155
  • 1
  • 2
12

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

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

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.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
  • This is much easier to read and more user friendly than the old way but not many people know about it. Deserves an upvote. – jonas dufek Feb 16 '22 at 20:36
  • 1
    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ørn Stenfeldt Sep 23 '22 at 07:58
  • 1
    @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. – M. Justin Sep 23 '22 at 16:57
  • @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);` – M. Justin May 15 '23 at 17:53
10
private static Random random = new Random();    

public static int getRandomInt(int min, int max){
  return random.nextInt(max - min + 1) + min;
}

OR

public static int getRandomInt(Random random, int min, int max)
{
  return random.nextInt(max - min + 1) + min;
}
GAMITG
  • 3,810
  • 7
  • 32
  • 51
8
Random rng = new Random();
int min = 3;
int max = 11;
int upperBound = max - min + 1; // upper bound is exclusive, so +1
int num = min + rng.nextInt(upperBound);
System.out.println(num);
swpalmer
  • 3,890
  • 2
  • 23
  • 31
Shital Ghimire
  • 101
  • 1
  • 5
7

If you already use Commons Lang API 3.x or latest version then there is one class for random number generation RandomUtils.

public static int nextInt(int startInclusive, int endExclusive)

Returns a random integer within the specified range.

Parameters:

startInclusive - the specified starting value

endExclusive - the specified end value

int random = RandomUtils.nextInt(999,1000000);

Note: In RandomUtils have many methods for random number generation

Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44
7
int randomNum = 5 + (int)(Math.random()*5);

Range 5-10

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Musfiq Shanta
  • 1,298
  • 13
  • 9
6

You can use this code snippet which will resolve your problem:

Random r = new Random();
int myRandomNumber = 0;
myRandomNumber = r.nextInt(maxValue - minValue + 1) + minValue;

Use myRandomNumber (which will give you a number within a range).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sachit
  • 1,128
  • 2
  • 12
  • 25
6

I will simply state what is wrong with the solutions provided by the question and why the errors.

Solution 1:

randomNum = minimum + (int)(Math.random()*maximum); 

Problem: randomNum is assigned values numbers bigger than maximum.

Explanation: Suppose our minimum is 5, and your maximum is 10. Any value from Math.random() greater than 0.6 will make the expression evaluate to 6 or greater, and adding 5 makes it greater than 10 (your maximum). The problem is you are multiplying the random number by the maximum (which generates a number almost as big as the maximum) and then adding the minimum. Unless the minimum is 1, it's not correct. You have to switch to, as mentioned in other answers

randomNum = minimum + (int)(Math.random()*(maximum-minimum+1))

The +1 is because Math.random() will never return 1.0.

Solution 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

Your problem here is that '%' may return a negative number if the first term is smaller than 0. Since rn.nextInt() returns negative values with ~50% chance, you will also not get the expected result.

This, was, however, almost perfect. You just had to look a bit further down the Javadoc, nextInt(int n). With that method available, doing

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt(n);
randomNum =  minimum + i;

Would also return the desired result.

GAMITG
  • 3,810
  • 7
  • 32
  • 51
Jorge
  • 1,574
  • 2
  • 12
  • 14
  • 1
    % has even bigger problem of distribution bias. I wrote a blog post about it recently: https://jaroslawpawlak.wordpress.com/2014/10/11/random-number-generator-using-modulo/ – Jaroslaw Pawlak Mar 09 '15 at 15:52
6
import java.util.Random; 

public class RandomUtil {
    // Declare as class variable so that it is not re-seeded every call
    private static Random random = new Random();

    /**
     * Returns a psuedo-random number between min and max (both inclusive)
     * @param min Minimim value
     * @param max Maximim value. Must be greater than min.
     * @return Integer between min and max (both inclusive)
     * @see java.util.Random#nextInt(int)
     */
    public static int nextInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return random.nextInt((max - min) + 1) + min;
    }
}
GAMITG
  • 3,810
  • 7
  • 32
  • 51
yottabrain
  • 2,387
  • 5
  • 23
  • 37
6

A different approach using Java 8 IntStream and Collections.shuffle

import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args) {

        IntStream range = IntStream.rangeClosed(5,10);
        ArrayList<Integer> ls =  new ArrayList<Integer>();

        //populate the ArrayList
        range.forEach(i -> ls.add(new Integer(i)) );

        //perform a random shuffle  using the Collections Fisher-Yates shuffle
        Collections.shuffle(ls);
        System.out.println(ls);
    }
}

The equivalent in Scala

import scala.util.Random

object RandomRange extends App{
  val x =  Random.shuffle(5 to 10)
    println(x)
}
firephil
  • 830
  • 10
  • 18
  • Nice. You could use `List ls = range.boxed().collect(Collectors.toList());` – Eric Duminil Feb 27 '17 at 20:27
  • new Integer(i) was also redundant, but it gets removed by the code in my previous comment anyway. – Eric Duminil Feb 27 '17 at 20:28
  • 1
    Doesn't this provide 6 numbers in a random order rather than a single number? Seems a bit wasteful. And should I want another random number I can't just take the second in the list because it has no chance of being the same as the number already taken. – charles-allen Aug 02 '17 at 13:44
5

I am thinking to linearly normalize the generated random numbers into desired range by using the following. Let x be a random number, let a and b be the minimum and maximum range of desired normalized number.

Then below is just a very simple code snipplet to test the range produced by the linear mapping.

public static void main(String[] args) {
    int a = 100;
    int b = 1000;
    int lowest = b;
    int highest = a;
    int count = 100000;
    Random random = new Random();
    for (int i = 0; i < count; i++) {
        int nextNumber = (int) ((Math.abs(random.nextDouble()) * (b - a))) + a;
        if (nextNumber < a || nextNumber > b) {
            System.err.println("number not in range :" + nextNumber);
        }
        else {
            System.out.println(nextNumber);
        }
        if (nextNumber < lowest) {
            lowest = nextNumber;
        }
        if (nextNumber > highest) {
            highest = nextNumber;
        }
    }
    System.out.println("Produced " + count + " numbers from " + lowest
            + " to " + highest);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

You could use the

RandomStringUtils.randomNumeric(int count)

method which is also from Apache Commons.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Venugopal Madathil
  • 2,031
  • 3
  • 34
  • 44
5
Random random = new Random();
int max = 10;
int min = 3;
int randomNum = random.nextInt(max) % (max - min + 1) + min;
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
namezhouyu
  • 224
  • 2
  • 4
5

The following code could be used:

ThreadLocalRandom.current().nextInt(rangeStart, rangeEndExclusive)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anshul Singhal
  • 1,983
  • 20
  • 25
  • 3
    There have been multiple answers that already suggested `ThreadLocalRandom`. If a question has been protected then please take extra care not to duplicate answers. – Maarten Bodewes Jul 01 '19 at 11:28
5

You can use the following way to do that:

int range = 10;
int min = 5
Random r = new Random();
int = r.nextInt(range) + min;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hasee Amarathunga
  • 1,901
  • 12
  • 17
4

I just generate a random number using Math.random() and multiply it by a big number, let's say 10000. So, I get a number between 0 to 10,000 and call this number i. Now, if I need numbers between (x, y), then do the following:

i = x + (i % (y - x));

So, all i's are numbers between x and y.

To remove the bias as pointed out in the comments, rather than multiplying it by 10000 (or the big number), multiply it by (y-x).

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
jatin3893
  • 832
  • 1
  • 11
  • 24
4

You can do something like this:

import java.awt.*;
import java.io.*;
import java.util.*;
import java.math.*;

public class Test {

    public static void main(String[] args) {
        int first, second;

        Scanner myScanner = new Scanner(System.in);

        System.out.println("Enter first integer: ");
        int numOne;
        numOne = myScanner.nextInt();
        System.out.println("You have keyed in " + numOne);

        System.out.println("Enter second integer: ");
        int numTwo;
        numTwo = myScanner.nextInt();
        System.out.println("You have keyed in " + numTwo);

        Random generator = new Random();
        int num = (int)(Math.random()*numTwo);
        System.out.println("Random number: " + ((num>numOne)?num:numOne+num));
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thangaraj
  • 525
  • 5
  • 5
4

This is the easy way to do this.

import java.util.Random;
class Example{
    public static void main(String args[]){
        /*-To test-
        for(int i = 1 ;i<20 ; i++){
            System.out.print(randomnumber()+",");
        }
        */

        int randomnumber = randomnumber();

    }

    public static int randomnumber(){
        Random rand = new Random();
        int randomNum = rand.nextInt(6) + 5;

        return randomNum;
    }
}

In there 5 is the starting point of random numbers. 6 is the range including number 5.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Gihan Chathuranga
  • 442
  • 10
  • 16
4

Say you want range between 0-9, 0 is minimum and 9 is maximum. The below function will print anything between 0 and 9. It's the same for all ranges.

public static void main(String[] args) {
    int b = randomNumberRange(0, 9);
    int d = randomNumberRange (100, 200);
    System.out.println("value of b is " + b);
    System.out.println("value of d is " + d);
}

public static int randomNumberRange(int min, int max) {
    int n = (max + 1 - min) + min;
    return (int) (Math.random() * n);
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sidd Thota
  • 2,040
  • 1
  • 20
  • 24
  • This doesn't look right. In "int n = (max + 1 - min) + min; return (int) (Math.random() * n);" , n = max + 1, and you are just creating an int in [0, max] instead of [min, max]. It should be "int n = max + 1 - min; return (int) (Math.random() * n) + min;" – user10253771 Jan 23 '19 at 01:03
4

Making the following change in Attempt 1 should do the work -

randomNum = minimum + (int)(Math.random() * (maximum - minimum) );

Check this for working code.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
monster
  • 808
  • 10
  • 23
4
int func(int max, int min){

      int range = max - min + 1;
      
      // Math.random() function will return a random no between [0.0,1.0).
      int res = (int) ( Math.random()*range)+min;

      return res;
}
commonpike
  • 10,499
  • 4
  • 65
  • 58
Lokesh Sharma
  • 411
  • 5
  • 6
3

One of my friends had asked me this same question in university today (his requirements was to generate a random number between 1 & -1). So I wrote this, and it works fine so far with my testing. There are ideally a lot of ways to generate random numbers given a range. Try this:

Function:

private static float getRandomNumberBetween(float numberOne, float numberTwo) throws Exception{

    if (numberOne == numberTwo){
        throw new Exception("Both the numbers can not be equal");
    }

    float rand = (float) Math.random();
    float highRange = Math.max(numberOne, numberTwo);
    float lowRange = Math.min(numberOne, numberTwo);

    float lowRand = (float) Math.floor(rand-1);
    float highRand = (float) Math.ceil(rand+1);

    float genRand = (highRange-lowRange)*((rand-lowRand)/(highRand-lowRand))+lowRange;

    return genRand;
}

Execute like this:

System.out.println( getRandomNumberBetween(1,-1));
GAMITG
  • 3,810
  • 7
  • 32
  • 51
Arun Abraham
  • 4,011
  • 14
  • 54
  • 75
  • Try other ranges, your code does not produce the uniform values in the given range. numberOne = 3.5 and numberTwo = 7.2 only produces values in the range 4.73..5.96. – Warren MacEvoy Aug 17 '16 at 22:25
3

This will generate Random numbers list with range (Min - Max) with no duplicate.

generateRandomListNoDuplicate(1000, 8000, 500);

Add this method.

private void generateRandomListNoDuplicate(int min, int max, int totalNoRequired) {
    Random rng = new Random();
    Set<Integer> generatedList = new LinkedHashSet<>();
    while (generatedList.size() < totalNoRequired) {
        Integer radnomInt = rng.nextInt(max - min + 1) + min;
        generatedList.add(radnomInt);
    }
}

Hope this will help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • 1
    This becomes tricky once you have found most of the numbers within the range; there are more efficient ways of doing this (e.g. generating a random number with a max equal to the number of elements remaining, and skipping already found numbers. Like Bingo really. – Maarten Bodewes Mar 01 '17 at 21:39
  • Yes, this will become very very slow. Yet another [Shlemiel the painter’s algorithm](https://www.joelonsoftware.com/2001/12/11/back-to-basics/)? Or even worse? Can you add some timing information to quantify the problem, e.g. for min = 1 and max = 1000000? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) – Peter Mortensen Apr 22 '22 at 14:07
3

I have created a method to get a unique integer in a given range.

/*
      * minNum is the minimum possible random number
      * maxNum is the maximum possible random number
      * numbersNeeded is the quantity of random number required
      * the give method provides you with unique random number between min & max range
*/
public static Set<Integer> getUniqueRandomNumbers( int minNum , int maxNum ,int numbersNeeded ){

    if(minNum >= maxNum)
        throw new IllegalArgumentException("maxNum must be greater than minNum");

    if(! (numbersNeeded > (maxNum - minNum + 1) ))
        throw new IllegalArgumentException("numberNeeded must be greater then difference b/w (max- min +1)");

    Random rng = new Random(); // Ideally just create one instance globally

    // Note: use LinkedHashSet to maintain insertion order
    Set<Integer> generated = new LinkedHashSet<Integer>();
    while (generated.size() < numbersNeeded)
    {
        Integer next = rng.nextInt((maxNum - minNum) + 1) + minNum;

        // As we're adding to a set, this will automatically do a containment check
        generated.add(next);
    }
    return generated;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
3

The below code generates a random number between 100,000 and 900,000. This code will generate six digit values. I'm using this code to generate a six-digit OTP.

Use import java.util.Random to use this random method.

import java.util.Random;

// Six digits random number generation for OTP
Random rnd = new Random();
long longregisterOTP = 100000 + rnd.nextInt(900000);
System.out.println(longregisterOTP);
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
BMAM
  • 73
  • 1
  • 2
  • 9
3

The following is another example using Random and forEach

int firstNum = 20;//Inclusive
int lastNum = 50;//Exclusive
int streamSize = 10;
Random num = new Random().ints(10, 20, 50).forEach(System.out::println);
Sanjeev Singh
  • 51
  • 1
  • 6
3

Use java.util for Random for general use.

You can define your minimum and maximum range to get those results.

Random rand=new Random();
rand.nextInt((max+1) - min) + min;
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Prakhar Nigam
  • 678
  • 3
  • 15
3

Use Apache Lang3 Commons

Integer.parseInt(RandomStringUtils.randomNumeric(6, 6));

Min Value 100000 to Max Value 999999

Anand
  • 1,845
  • 2
  • 20
  • 25
  • Why make life so complicated when it is possible to have simple solutions :) – user2719152 Jul 09 '20 at 03:34
  • I thought, this was simplest given random numbers in a range. – Anand Jul 09 '20 at 11:23
  • Generated number can start with a zero! – Saikat Jul 28 '20 at 07:32
  • This produces a string, not an integer, and is therefore not an answer to the question. – Raimund Krämer Nov 22 '20 at 13:25
  • It returns \p{Digit} – Anand Nov 24 '20 at 12:20
  • Yes, exactly, [like the doc says](https://commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/apache/commons/lang3/RandomStringUtils.html#randomNumeric-int-int-) *Characters will be chosen from the set of `\p{Digit}` characters.* It does *not* special case the first digit to be any different from the later digits. Since 0 is a digit, making it possible to randomly generate `"100000"`, it's also possible to randomly generate `"000000"`. Did you test this? 1 in 10 times it should generate a leading zero and be outside your range, unless I'm misreading the docs. – Peter Cordes Apr 26 '22 at 12:36
  • 1
    `RandomStringUtils.randomNumeric` is not for generating random *numbers* in string form. It's for generating random strings, whose characters happen to be chosen from the 0-9 digits. That's why leading-zeros are allowed, making it not useful even for the kinds of ranges this answer suggests. – Peter Cordes Apr 26 '22 at 12:38
2

I think this code will work for it. Please try this:

import java.util.Random;
public final class RandomNumber {

    public static final void main(String... aArgs) {
        log("Generating 10 random integers in range 1..10.");
        int START = 1;
        int END = 10;
        Random randomGenerator = new Random();
        for (int idx=1; idx<=10; ++idx) {

            // int randomInt=randomGenerator.nextInt(100);
            // log("Generated : " + randomInt);
            showRandomInteger(START,END,randomGenerator);
        }
        log("Done");
    }

    private static void log(String aMessage) {
        System.out.println(aMessage);
    }

    private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        long range = (long)aEnd - (long)aStart + 1;
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int) (fraction + aStart);
        log("Generated" + randomNumber);
    }
}
GAMITG
  • 3,810
  • 7
  • 32
  • 51
Akash Malhotra
  • 367
  • 1
  • 12
2

You can either use the Random class to generate a random number and then use the .nextInt(maxNumber) to generate a random number. The maxNumber is the number that you want the maximum when generating a random number. Please remember though, that the Random class gives you the numbers 0 through maxNumber-1.

Random r = new Random();
int i = r.nextInt();

Another way to do this is to use the Math.Random() class which many classes in schools require you to use because it is more efficient and you don't have to declare a new Random object. To get a random number using Math.Random() you type in:

Math.random() * (max - min) + min;
GAMITG
  • 3,810
  • 7
  • 32
  • 51
f3d0r
  • 541
  • 3
  • 12
  • 27
2

Random number from the range [min..max] inclusive:

int randomFromMinToMaxInclusive = ThreadLocalRandom.current()
        .nextInt(min, max + 1);
Andrew
  • 36,676
  • 11
  • 141
  • 113
  • An explanation would be in order. E.g., what is the idea/gist? What is this thread thing? Why is it necessary? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/33424282/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Apr 22 '22 at 14:05
2

Most of previous suggestions don't consider 'overflow'. For example: min = Integer.MIN_VALUE, max = 100. One of the correct approaches I have so far is:

final long mod = max- min + 1L;
final int next = (int) (Math.abs(rand.nextLong() % mod) + min);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user_3380739
  • 1
  • 14
  • 14
  • Creating guard statements (if value > other value then exception) should also work (presuming the range isn't set by user / system input). – Maarten Bodewes Jun 19 '17 at 21:29
2

There is a library at https://sourceforge.net/projects/stochunit/ for handling selection of ranges.

StochIntegerSelector randomIntegerSelector = new StochIntegerSelector();
randomIntegerSelector.setMin(-1);
randomIntegerSelector.setMax(1);
Integer selectInteger = randomIntegerSelector.selectInteger();

It has edge inclusion/preclusion.

ledlogic
  • 774
  • 1
  • 9
  • 19
2
import java.util.Random;

public class RandomSSNTest {

    public static void main(String args[]) {
        generateDummySSNNumber();
    }


    //831-33-6049
    public static void generateDummySSNNumber() {
        Random random = new Random();

        int id1 = random.nextInt(1000);//3
        int id2 = random.nextInt(100);//2
        int id3 = random.nextInt(10000);//4

        System.out.print((id1+"-"+id2+"-"+id3));
    }

}

You can also use

import java.util.concurrent.ThreadLocalRandom;
Random random = ThreadLocalRandom.current();

However, this class doesn’t perform well in a multi-threaded environment.

vaquar khan
  • 10,864
  • 5
  • 72
  • 96
  • 1
    The whole point of ThreadLocalRandom is higher performance by letting each thread generate random numbers independently, without locking or other interaction with state shared across threads. Also, this answer doesn't show how to use a range where the min isn't zero, or the range method that ThreadLocalRandom provides. But other answers do, so this doesn't seem to be adding much new information for future readers. – Peter Cordes Apr 26 '22 at 12:46
2

To avoid repeating what have been said multiple times, I am showing an alternative for those that need a cryptographically stronger pseudo-random number generator by using the SecureRandom class, which extends the class Random. From source one can read:

This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1. Additionally, SecureRandom must produce non-deterministic output. Therefore any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong, as described in RFC 1750: Randomness Recommendations for Security.

A caller obtains a SecureRandom instance via the no-argument constructor or one of the getInstance methods:

  SecureRandom random = new SecureRandom();  

Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.

To generate a random number between a min and max values inclusive:

public static int generate(SecureRandom secureRandom, int min, int max) {
        return min + secureRandom.nextInt((max - min) + 1);
}

for a given a min (inclusive) and max (exclusive) values:

return min + secureRandom.nextInt((max - min));

A running code example:

public class Main {

    public static int generate(SecureRandom secureRandom, int min, int max) {
        return min + secureRandom.nextInt((max - min) + 1);
    }

    public static void main(String[] arg) {
        SecureRandom random = new SecureRandom();
        System.out.println(generate(random, 0, 2 ));
    }
}

Source such as stackoverflow, baeldung, geeksforgeeks provide comparisons between Random and SecureRandom classes.

From baeldung one can read:

The most common way of using SecureRandom is to generate int, long, float, double or boolean values:

int randomInt = secureRandom.nextInt();
long randomLong = secureRandom.nextLong();
float randomFloat = secureRandom.nextFloat();
double randomDouble = secureRandom.nextDouble();
boolean randomBoolean = secureRandom.nextBoolean();

For generating int values we can pass an upper bound as a parameter:

int randomInt = secureRandom.nextInt(upperBound);

In addition, we can generate a stream of values for int, double and long:

IntStream randomIntStream = secureRandom.ints();
LongStream randomLongStream = secureRandom.longs();
DoubleStream randomDoubleStream = secureRandom.doubles();

For all streams we can explicitly set the stream size:

IntStream intStream = secureRandom.ints(streamSize);

This class offers several other options (e.g., choosing the underlying random number generator) that are out of the scope of this question.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
1

Try using org.apache.commons.lang.RandomStringUtils class. Yes, it sometimes give a repeated number adjacently, but it will give the value between 5 and 15:

    while (true)
    {
        int abc = Integer.valueOf(RandomStringUtils.randomNumeric(1));
        int cd = Integer.valueOf(RandomStringUtils.randomNumeric(2));
        if ((cd-abc) >= 5 && (cd-abc) <= 15)
        {
            System.out.println(cd-abc);
            break;
        }
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
0

Using Java 8 Streams,

  • Pass the initialCapacity - How many numbers
  • Pass the randomBound - from x to randomBound
  • Pass true/false for sorted or not
  • Pass an new Random() object

 

public static List<Integer> generateNumbers(int initialCapacity, int randomBound, Boolean sorted, Random random) {

    List<Integer> numbers = random.ints(initialCapacity, 1, randomBound).boxed().collect(Collectors.toList());

    if (sorted)
        numbers.sort(null);

    return numbers;
}

It generates numbers from 1-Randombound in this example.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jake O
  • 64
  • 1
  • Where is the streams stuff in this solution? The `random.ints` part? What does it do? What problem does it solve? An explanation would be in order. – Peter Mortensen Apr 22 '22 at 14:13
0

A simple way to generate n random numbers between a and b e.g a =90, b=100, n =20

Random r = new Random();
for(int i =0; i<20; i++){
    System.out.println(r.ints(90, 100).iterator().nextInt());
}

r.ints() returns an IntStream and has several useful methods, have look at its API.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sam2016
  • 1,014
  • 7
  • 13
  • 1
    Besides there being other answers that use streams, at least they don't create a new stream within a loop, now that really doesn't make sense. – Maarten Bodewes May 05 '20 at 19:51
0
public static void main(String[] args) {

    Random ran = new Random();

    int min, max;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter min range:");
    min = sc.nextInt();
    System.out.println("Enter max range:");
    max = sc.nextInt();
    int num = ran.nextInt(min);
    int num1 = ran.nextInt(max);
    System.out.println("Random Number between given range is " + num1);

}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Alekya
  • 239
  • 5
  • 15
0

Here's a function that returns exactly one integer random number in a range defined by lowerBoundIncluded and upperBoundIncluded, as requested by user42155

SplittableRandom splittableRandom = new SplittableRandom();

BiFunction<Integer,Integer,Integer> randomInt = (lowerBoundIncluded, upperBoundIncluded)
    -> splittableRandom.nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

randomInt.apply( …, … ); // gets the random number


…or shorter for the one-time generation of a random number

new SplittableRandom().nextInt(lowerBoundIncluded, upperBoundIncluded + 1);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kaplan
  • 2,572
  • 13
  • 14
0

If you don't want to reinvent the wheel, here is a one-liner, no-brainer solution:

RandomStringUtils.randomNumeric(count); // Where count is the number of digits you want in the random number.

Apache Commons, e.g. RandomUtils in component Lang, provides many options to generate whatever format of random number you wish for.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
saran3h
  • 12,353
  • 4
  • 42
  • 54
0

Because the Android question redirects here, this is how you would do it with Kotlin:

val r = (0..10).random() // A random integer between 0 and 10 inclusive

This works with Kotlin 1.3 and higher. Refer to this answer.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
0

Generate random integers within a specific range in Java

  • Short Way
       public class Main {
          public static void main(String[] args) {
             int randomNum = new Random().nextInt(41) + 10; // 10 to 50
             System.out.println("Random Number: " + randomNum);
        }
      }
    
  • Long way
       public class Main {
           public static void main(String[] args) {
               Random rand = new Random();
    
               int lowerBound = 10;
               int upperBound = 50;
    
               int randomNum = rand.nextInt((upperBound - lowerBound) + 1) + lowerBound;
    
               System.out.println("Random Number: " + randomNum);
           }
        }
    
-6

You can do as below.

import java.util.Random;
public class RandomTestClass {

    public static void main(String[] args) {
        Random r = new Random();
        int max, min;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter maximum value : ");
        max = scanner.nextInt();
        System.out.println("Enter minimum value : ");
        min = scanner.nextInt();
        int randomNum;
        randomNum = r.nextInt(max) + min;
        System.out.println("Random Number : " + randomNum);
    }

}