简体   繁体   English

返回一个只有奇数的数组

[英]Returning an array of only odd numbers

I need to return an array of only the odd numbers, eg [1,3,5] .我需要返回一个只有奇数的数组,例如[1,3,5] I've been asked to do this as part of my schooling and I cant see where I'm going wrong.我被要求这样做作为我学习的一部分,我看不出我哪里出错了。

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 you wanna return odds from an array you should pass it as parameter first, aslo you should store your odds in a new array after the IF statement.如果你想从一个数组中返回赔率,你应该首先将它作为参数传递,你也应该在 IF 语句之后将你的赔率存储在一个新数组中。 You should use at the first time a dynamic list becouse you don't know how many odds are there, after you can easely convert the ArrayList to a normal Array.您应该在第一次使用动态列表,因为您不知道有多少赔率,之后您可以轻松地将 ArrayList 转换为普通 Array。 Something like this:像这样的东西:

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

Here is your code as posted.这是您发布的代码。 See my comments below看我下面的评论

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

You could save time this way with native Java 8 streams API :您可以通过本机 Java 8 流 API 以这种方式节省时间:

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

Streams provides many methods to make your job quick Streams 提供了许多使您的工作快速进行的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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