Naveen Kumar
Naveen Kumar

Reputation: 65

Java function is not returning expected value

A bug in a program I'm writing as an assignment for my java. Objective: program should take two parameters and find all the odd numbers between those parameters. Then it should return the sum of all those numbers.

Bug: When the parameters are negative or starting number is greater than the ending number, it should return -1. But my program is returning 0.

Maybe my program isn't updating the sum value inside the loop. But even so, as per return condition, my function should return -1, not the sum.

public class SumOddRange{
    public static void main(String[] args){
        System.out.println(sumOdd(10,5));
    }
    
    public static boolean isOdd(int number){
        return (number<0)||(number%2==0)?false:true;
    }
    
    public static int sumOdd(int start, int end){

        int sum = 0;
        for(int i=start; i<=end; i++){
            if(isOdd(i)){
                sum+=i;
            }
        }
        return (start<=0)&&(start>end)? -1: sum;
    }
}

Upvotes: 1

Views: 232

Answers (2)

Sadiq Raza
Sadiq Raza

Reputation: 354

There is a logic error in your line return (start<=0)&&(start>end)? -1: sum;

You have to return -1 if start is <0 or start > end, so use "||" (logical Or) instead of "&&" (logical and):

return (start<=0)||(start>end)? -1: sum;

Please go through @luk2302's answer for a better solution.

Upvotes: 1

luk2302
luk2302

Reputation: 57114

Put the input check as the first thing in your method and change the && to an || since you want to return if the first check fails or the second check fails, not only if both fail. And the isOdd can be inlined:

public static int sumOdd(int start, int end){
    if (start <= 0 || start > end)
        return -1;

    int sum = 0;
    for (int i = start; i <= end; i++) {
        if (i % 2 != 0) { // or if (i % 2 == 1) {
            sum += i;
        }
    }
    return sum;
}

Upvotes: 3

Related Questions