簡體   English   中英

在Java中,我想使用for循環從整數數組中提取奇數位置的每個數字。 我犯了什么錯誤?

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

所以這是我從整數數組中提取的方法(該數組的長度是偶數)。

 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;
  }

而且它沒有用。 我嘗試在每個循環中打印出新數組oddNumbers內的情況,以調試此方法。 我使用1 2 8 4 6 9作為此方法的參數。 我發現一個非常奇怪的條件是, 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然而在第一循環中的oddNumbers是1, 0, 0, 2 2來自哪里...? 我期望這種方法的最終結果是1, 8, 6但它給了我6, 0, 0 那么我的方法有什么問題呢? 謝謝!

怎么樣,而不是循環遍歷每個索引然后測試是否奇數,而是從1開始循環,每次都增加2:

例:

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

您應該像@Conner G一樣進行操作,但是在這里,只是為了顯示您的錯誤,所以您不再做它:

int j = 0;

在錯誤的位置,您應該將其放在循環之前,因為它將在每次迭代時重置,因此您實際上將每個數字都放在index = 0上

這是一個設計問題,因為您不應該首先處理每個元素:

@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]

流程結束,退出代碼為0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM