Tony Chen Tony Chen - 2 months ago 7
Java Question

in java I want to use for loop to pull out every number in odd position from integer array. what bug did I make?

So this is my method to pull out from a integer array(the length of this array is an even number).

public static int[] oddPosition (int[] array) {
int [] oddNumbers = new int[array.length / 2];
for (int i = 0; i < array.length; i++) {
int j = 0;
//System.out.println(i);//test
//printArray(oddNumbers); //test
if ((i + 1) % 2 != 0) {
//System.out.println(i);//test
oddNumbers[j] = array[i];
j ++;
}
}
return oddNumbers;
}


And it didn't work. I try to print out the situation inside my new array
oddNumbers
at every loop to debug this method. I used
1 2 8 4 6 9
as my parameter to this method.
I find a very strange condition is that
when i = 0, (i + 1) % 2 != 0, then array[0](which is 1) should be assigned to oddNumbers[0]. and oddNumbers should be [1, 0, 0, 0] at first loop
however the oddNumbers at first loop is
1, 0, 0, 2
. Where is the 2 coming from...? The final result of this method I expected is
1, 8, 6
but it gives me
6, 0, 0
. So what's wrong with my method? Thx!

Answer

How about, instead of looping through every index and then testing if it's odd, you start your loop at 1 and increase by 2 every time:

Example:

for(int i = 1; i < array.length; i+=2)
Comments