How do I generate a random integer between min and max in Java?

后端 未结 8 1241
醉酒成梦
醉酒成梦 2020-12-13 09:15

What method returns a random int between a min and max? Or does no such method exist?

What I\'m looking for is something like this:

NAMEOFMETHOD (mi         


        
相关标签:
8条回答
  • 2020-12-13 09:26

    Construct a Random object at application startup:

    Random random = new Random();
    

    Then use Random.nextInt(int):

    int randomNumber = random.nextInt(max + 1 - min) + min;
    

    Note that the both lower and upper limits are inclusive.

    0 讨论(0)
  • 2020-12-13 09:29

    With Java 7 or above you could use

    ThreadLocalRandom.current().nextInt(int origin, int bound)
    

    Javadoc: ThreadLocalRandom.nextInt

    0 讨论(0)
  • 2020-12-13 09:35

    import java.util.Random;

    0 讨论(0)
  • 2020-12-13 09:38

    As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

    public static int getRandom(int min, int max) {
        if (min > max) {
            throw new IllegalArgumentException("Min " + min + " greater than max " + max);
        }      
        return (int) ( (long) min + Math.random() * ((long)max - min + 1));
    }
    

    this works even if you call it with:

    getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 
    
    0 讨论(0)
  • 2020-12-13 09:40
    public static int random_int(int Min, int Max)
    {
         return (int) (Math.random()*(Max-Min))+Min;
    }
    
    random_int(5, 9); // For example
    
    0 讨论(0)
  • 2020-12-13 09:40

    Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

    min + (int) (Math.random() * (max - min + 1));
    
    0 讨论(0)
提交回复
热议问题