Here's the format I'm following:
int randomNum = rand.nextInt((max - min) + 1) + min;
So here's my code. I'm trying to get a random even number between 1 and 100:
Random rand = new Random();
int randomNum = rand.nextInt((100 - 2) + 1) + 2;
I saw one solution is to multiply the number by 2, but that breaches the intended range.
I thought of doing a bunch of if statements to solve this, but it seems overly complex. Is there a relatively simple solution?
Select a blank cell, and type this formula =EVEN(RANDBETWEEN(X,Y)) (X and Y indicate any integer numbers, and X<Y), for instance, I want to randomize even numbers between -5 and 10, now I type =EVEN(RANDBETWEEN(-5,10)) into an empty cell, press Enter key, if you need, you can drag the fill handle to a range with this ...
In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With