Marcel Franzen
Marcel Franzen

Reputation: 40

Generate random numbers that can be divided by 2

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

Answers (5)

Méhdi Màick
Méhdi Màick

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

Subhrajyoti Majumder
Subhrajyoti Majumder

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

user43968
user43968

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

NiallMitch14
NiallMitch14

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

Jean Logeart
Jean Logeart

Reputation: 53839

Simply:

int number = new Random().nextInt(10) * 2;

Upvotes: 4

Related Questions