sixGdie
sixGdie

Reputation: 1

Random even numbers on array from 1 to 100

I need to write on an array 20 random numbers from 1 to 100, but just even numbers.. For some reason i'm getting 0 on some array value, any solution for this?

for (int i = 0; i < 20; i++) {

Random random = new Random();
int randomNumber = random.nextInt(100) + 1;

if (randomNumber % 2 == 0) {
    arregloAleatorio[i] = randomNumber; 
}

The print is, for example:

0 26 0 4 0 14 0 78 0 16 0 0 86 10 0 0 0 72 34 70

But I don't want 0 in the array.

Upvotes: 0

Views: 708

Answers (3)

lime
lime

Reputation: 809

Try the following:

int[] arregloAleatorio = new int[20];
for (int i = 0; i < 20; i++) {
    Random random = new Random();
    int randomNumber = random.nextInt(101);
    while (randomNumber % 2 != 0 || randomNumber == 0){
        randomNumber = random.nextInt(101);
    }
    arregloAleatorio[i] = randomNumber;
}

You are not adding a number to the array if it is odd, therefore by default it was zero.

This solution generates a random number until it is not 0 or odd.

Upvotes: 0

Baromachine
Baromachine

Reputation: 21

This is happening because your iteration continues even if the number is odd, and when you are outputting the array, it appears to be a 0 because there is no number at that index! The quick fix would be to just decrement i if the number is odd. I am adding only 1 line of code. I didn't try it but it should work.

for (int i = 0; i < 20; i++) {

    Random random = new Random();
    int randomNumber = random.nextInt(100) + 1;

    if (randomNumber % 2 == 0) {
        
        arregloAleatorio[i] = randomNumber;
        
    }else i--;
    

Upvotes: 0

Tomer Shetah
Tomer Shetah

Reputation: 8529

I would suggest to think about the constraints first. We want to the generated numbers to be the even numbers, between 2 and 100. This group of numbers, is of the size of 50. Therefore, we can generate a random number between 0-49 (Inclusive), and then add 1 and multiply by 2, and get the required number. The code:

int[] arr = new int[20];
for (int i = 0; i < 20; i++) {
    Random random = new Random();
    int randomNumber = random.nextInt(50) + 1
    arr[i] = randomNumber * 2;
}

Upvotes: 1

Related Questions