Java

How to generate a random number within a range in Java

Here is a standard way to generate a random number within a specific range in Java.

Please note that in the below code, the top value (max) is exclusive and the min value is inclusive.

    public static int generateRandomNumber(int max, int min) {

        Random rand = new Random();
        int randomNum = rand.nextInt(max - min) + min;
        return randomNum;
    }

Here is the code to generate a random number with max and min value inclusive.

    public static int generateRandomNumber(int max, int min) {

        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s