Create array which stores odds from -6 to 38 in java

Tags:



I’m learning Java and I found an exercise which I can’t solve, in the Arrays chapter.

The exercise says:

Write code that creates an array named odds and stores all odd numbers between -6 and 38 into it using a for loop. Make the array’s size exactly large enough to store the numbers.

The only solution I could come up with is this:

import java.util.Arrays;

public class exerciseOddsArray {
    public static void main(String[]args){

        oddsArray();
    }
    public static void oddsArray(){
        int odds = 0;
        for (int i = -6; i <= 38; i++){
            if (i % 2 == 1){
                odds++;
            }
        }
        int[] numbers = new int[odds];
        for (int i = 0; i < numbers.length; i ++){
                for (int j = -6; j <= 38; j++){
                    if(j % 2 == 1){
                        numbers[i] = j;
                    }
            }
        }
        System.out.println(Arrays.toString(numbers));
    }
}

However, the program prints:

[37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37]

And I don’t understand why.

Answer

You don’t need nested FOR loops here. Just create an integer variable i to track your position in the array and increment it when adding each new item. PS… the array should have been called “odds” based on the specs of the assignment. I suggest renaming that variable you were using to count the number of odds to something else (e.g. numberOfOdds)

int[] odds= new int[numberOfOdds];
int i = 0;

for (int j = -6; j <= 38; j++)
{
  if(j % 2 == 1)
  {
      odds[i++] = j;
   }
}


Source: stackoverflow