Generate a random even number inside a range?

Here´s a tiny example on how to do it

static Random rand = new Random();

public static void main(String[] args) {
    for(int i = 0;i<100;++i)
        System.out.println(generateEvenNumber(0, 100));

}

private static int generateEvenNumber(int min, int max) {
    min = min % 2 == 1 ? min + 1 : min; // If min is odd, add one to make sure the integer division can´t create a number smaller min;
    max = max % 2 == 1 ? max - 1 : max; // If max is odd, subtract one to make sure the integer division can´t create a number greater max;
    int randomNum = ((rand.nextInt((max-min))+min)+1)/2; // Divide both by 2 to ensure the range
    return randomNum *2; // multiply by 2 to make the number even
}

After you get the random number between 1 and 100 and multiply it by 2, you can get the number % 100. Something like:

int random = rand.nextInt(100);
random = (random * 2) % 100;

This way number will always be less than 100 and even.


In Java 1.7 or later, I would use ThreadLocalRandom:

import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

The reason to use ThreadLocalRandom is explained here. Also note, that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.


Just generate a number from 0 to 49 and then multiply it by 2.

Random rand = new Random(); 
int randomNum = rand.nextInt(100/2) *2;

To do it in a range just add the range in:

int randomNum = startOfRange+rand.nextInt((endOfRange-startOfRange)/2) *2;

Note that startOfRange should be an even number or converted into an even number.

Tags:

Java

Random

Range