0

this is my first question on here so I'm not sure how everything works on StackOverflow. I know with an int you need to return something but for some reason, my code doesn't work. I tried all sorts of stuff to make this work but I have no clue anymore how I could solve this. Any help is greatly appreciated.

my code:

public class Main {

public static void main(String[] args) {

    System.out.println(isOdd(10));
    System.out.println(sumOdd(10, 50));

}


public static boolean isOdd(int number) {


    if (number < 0) {

        return false;


    } else if (number % 2 == 0) {

        return false;


    } else {

        return true;


    }

}

static public int sumOdd(int start, int end) {


    int sumOfOddNumbers = 0;

    for (int i = 0; i >= 50; i++) {


        if (isOdd(i) && end < 0 && start < 0 && end <= start) {


            sumOfOddNumbers += i;

            System.out.println("The sum of the odd numbers are " + sumOfOddNumbers);

        } else {


        return sumOfOddNumbers;


        }

    }

}

Ward095
  • 11
  • 1
  • `for (int i = 0; i >= 50; i++)` Your code in for-loop never starts because `i` starts with 0 and is never >= 50. Change the condition to `i <= end;` and move the `return` statement out of the for-loop – denvercoder9 Apr 21 '20 at 21:09
  • Write the function as `static public int sumOdd(int start, int end) { int sumOfOddNumbers = 0; for (int i = start; i <= end; i++) { if (isOdd(i)) { sumOfOddNumbers += i; } } System.out.println("The sum of the odd numbers are " + sumOfOddNumbers); return sumOfOddNumbers; }` – Arvind Kumar Avinash Apr 21 '20 at 21:11
  • Also, this whole part is wrong `end < 0 && start < 0 && end <= start` Why do you need to check those conditions? I'm just guessing here but you can just delete this condition and only keep `if (isOdd(i))` – denvercoder9 Apr 21 '20 at 21:11

1 Answers1

0

First your code isn't really good. The return statement work when i is not a odd number. So for i=1 return.

A better code can be this:

static public int sumOdd(int start, int end) {
    int sum = 0;
    if(!isOdd(start){ start++;}
    for(int i=start,i<end;i=i+2){
       sum += i;
    }
    return sum;
}
GG du 14
  • 29
  • 6