Ramish Khan Ramish Khan - 1 month ago 11
Java Question

Java - copying odd elements from array to another

this.blockHeights = new int[] { 1, 2, 1, 1, 2, 1, 2, 1 };

int x = blockHeights.length/2;

int leftSource[] = new int[x];
System.out.println(x);
int j = 0;

for (int i = 0; i < x; i++)
{
if ((blockHeights[i]%2 == 0) || (i == 0)) //odd-elements
{
leftSource[i] = blockHeights[i];
}

}

for (int i = 0; i < leftSource.length; i++)
{
System.out.println(leftSource[i]);
}


The output is 1, 2, 0, 0. Whereas my goal is to print out 1st, 3rd, 5th and 7th element from array blockHeights and put it in new array leftSource.

Answer Source

If you want to copy the odd index members to a new array (regardless of their value), like you said - 1st, 3rd, 5th and 7th - then try this:

this.blockHeights = new int[] { 1, 2, 1, 1, 2, 1, 2, 1 };

    int x = blockHeights.length/2;

    int leftSource[] = new int[x];
    System.out.println(x);
    //go over the larger array and skip by 2
    for (int i = 0; i < blockHeights.length; i=i+2)
    {  
       leftSource[i/2] = blockHeights[i];
    }

    for (int i = 0; i < leftSource.length; i++)
    {
        System.out.println(leftSource[i]);
    }