简体   繁体   中英

Returning an array of only odd numbers

I need to return an array of only the odd numbers, eg [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. 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. 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 :

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

Streams provides many methods to make your job quick

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