Reputation: 40
I need to generate random numbers that can be divided by 2 so : 2 4 6 8 10 12 14 16 18 .....
My code looks like:
Random random = new Random();
int i = random.nextInt(20);
Hopefully you know what I want and you can help me.
Upvotes: 2
Views: 3506
Reputation: 157
int number = 100; //number of numbers you want to generate
for(int i = 0; i < number; i++) {
int rand = random.nextInt(number);
while(rand % 2 != 0) {
rand = random.nextInt(number);
}
System.out.println(rand);
}
Upvotes: -1
Reputation: 41230
Deterministic approach -
Random random = new Random();
...
private int generateRandomDividedByTwo(){
int i = -1;
do{
i = random.nextInt(20);
}while(i%2!=0);
return i;
}
Upvotes: 0
Reputation: 2129
Just multiply i by 2
Random random = new Random();
int i = random.nextInt(20) * 2;
And adjust the random upper bound if you want to stay under 20 (replace by 10)
int i = random.nextInt(10) * 2;
The loop version is too heavy and ineficient in my opinion
Upvotes: 5
Reputation: 1229
Check the remainder/modulus of the result and if it is 1, add 1 to i to give an even number:
Random random = new Random();
int i = random.nextInt(20);
if(i%2 == 1){
i++;
}
Upvotes: 1