简体   繁体   中英

Returning and Summing the Odd Numbers of an Array

I'm trying to add all the odd numbers in an array and return it. Any thoughts on what I'm doing wrong?

Example:

Input:

Array- [12,6,7,15,1]

It would return 23

 public static int sumOdds(int[] numbers) {
            sum = 0;
            for(int i = 0; i < numbers.length; i++) {
                if (numbers%2==0) 
                return 0;
                else (numbers[i] % 2 != 0) {
                    sum += numbers;
                    return sumOdds; 
                    }
            }
public static int sumOdds(int[] numbers) {
   int sum = 0;
   for(int i = 0; i < numbers.length; i++) {
       if(numbers[i] % 2 != 0) {
           sum += numbers[i];                
       }
   }         
   return sum;
}

This should work. return statements should not be within your if and else statements, as they will end the execution of the program immediately.

And a Java 8+ solution would be

  public static int sumOdds(int[] numbers) {
      return Arrays.stream(numbers).filter(n -> n % 2 == 1).sum();
  }

There are a few issues here. First of all, the mod operation is not going to work on an array. It needs to be performed on a single number. Furthermore, you are immediately returning the sumOdds without allowing the entire loop to complete.

This would work.

public static int sumOdds(final int[] numbers) {
    int sumOdds = 0;
    for (int number : numbers) {
        if (number % 2 != 0) {
            sumOdds += number;
        }
    }
    return sumOdds;
}

Or better yet, use streams.

int sumOdds = IntStream.of(12, 6, 7, 15, 1).filter(number -> number % 2 != 0).sum()

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