簡體   English   中英

返回一個只有奇數的數組

[英]Returning an array of only odd numbers

我需要返回一個只有奇數的數組,例如[1,3,5] 我被要求這樣做作為我學習的一部分,我看不出我哪里出錯了。

public static int[] odds(int numOdds) {
    int[] odds = numOdds;
    for (int i=0; i<odds.length; i++) {
        if (odds[i] %2 != 0) {
            return odds;
        }
    }
}

public static void main(String[] args) {
    int[] theOdds = odds(3);
    System.out.println(theOdds[0] + ", " + theOdds[1] + ", " + theOdds[2]);
}

如果你想從一個數組中返回賠率,你應該首先將它作為參數傳遞,你也應該在 IF 語句之后將你的賠率存儲在一個新數組中。 您應該在第一次使用動態列表,因為您不知道有多少賠率,之后您可以輕松地將 ArrayList 轉換為普通 Array。 像這樣的東西:

public static int[] odds(int[] arrayOfNumber) {

List<Integer> odds = new ArrayList<Integer>();

for (int i=0; i<arrayOfNumber.length; i++) {
    if (arrayOfNumber[i] %2 != 0) {
        odds.add(arrayOfNumber[i]);
    }
  }
  return odds.toArray();
}

這是您發布的代碼。 看我下面的評論

public static int[] odds(int numOdds) {
    //   int[] odds = numOdds;     // needs to be int[] odds = new int[numOdds] to 
                                   //store the values.  It is the array you will 
                                   // return.
    int[] odds = new int[numOdds];

    int start = 1;            // you need to have a starting point
    for (int i=0; i<odds.length; i++) {
    //    if (odds[i] %2 != 0) { // don't need this as you are generating odd 
                                 // numbers yourself


    //    return odds;      // You're doing this too soon.  You need to store 
                               // the numbers in the array first 

          odds[i] = start;  // store the first odd number
          start += 2;       // this generates the next odd number.  Remember that
                            // every other number is even or odd depending from
                            // where you start.

    }
    return odds;         // now return the array of odd numbers.

    }
}

public static void main(String[] args) {
    int[] theOdds = odds(3);
    System.out.println(theOdds[0] + ", " + theOdds[1] + ", " + theOdds[2]);
}

您可以通過本機 Java 8 流 API 以這種方式節省時間:

int[] odds = Arrays.stream(arrayOfNumbers).filter(number -> number%2 != 0).toArray();

Streams 提供了許多使您的工作快速進行的方法

暫無
暫無

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

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