Trying to calculate sum of odd numbers in given range (java) – bug in a code? [closed]

Tags: ,



I am taking an Udemy course, and I have a problem with a challenge. The author seems to be unwilling to give any advice, so I am asking here.

THe challenge is to create a code using for loop that will calculate sum of odd numbers in any given range (range is defined by ‘start’ and ‘end’ parameters). First method (isOdd) checks if the number is odd, the second calculates the sum.

InteliJ gives me now warnings or errors, but when testing, the code is not displaying correct results. I have no idea where the bug is. Can anybody help?

public class SumOddRange {
  public static boolean isOdd(int number) {
        if (number < 0) {
            return false;
        } else if (number % 2 > 0) {
            return true;
        } else {
            return false;
        }

    }

   public static int sumOdd (int start, int end) {
        int sum = 0;
        for (int i = start; i <= end; i++) {

            if (isOdd(i) && end >= start && start > 0) {
                sum += i;
                return sum;
            }
        }
        return -1;
   }
}

Answer

The problem is that you return the sum on first odd number you meet. Modify it like this, to return the sum only at the end to consider whole range:

public class SumOddRange {
  public static boolean isOdd(int number) {
        if (number < 0) {
            return false;
        } else if (number % 2 > 0) {
            return true;
        } else {
            return false;
        }

    }

   public static int sumOdd (int start, int end) {
        int sum = 0;
        for (int i = start; i <= end; i++) {

            if (isOdd(i)) {
                sum += i;
            }
        }
        return sum;
   }
}


Source: stackoverflow