简体   繁体   中英

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 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!

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)

You should do it like @Conner G, but here, just to show your mistake so you don't do it again:

int j = 0;

is in the wrong place, you should put it before the loop, since it will be reset on every iteration, so you actually put every numbers on index = 0

It's a design issue as you should not step through each element in first place:

@Test
public void foo() {
  int[] array = new int[]{1,2,3,4,5,6,7,8,9};
  List<Integer> res = Lists.newArrayList();
  for (int i = 0; i < array.length; i+=2) {
    res.add(array[i]);
  }

  System.out.print(res);
}

[1, 3, 5, 7, 9]

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM