Batuhan Tüter
Batuhan Tüter

Reputation: 311

Missing Return Statement(Java)

What I'm trying to do is; I have given a sorted array such as; 1,1,1,2,2,3. Then I'm given a number such as; 6. Then I'm trying to find minimum number of array elements that I have to sum to find this number. I start from the end of the array to sum elements. The answer should be 3 because I used 3 items in the array to sum just like;

3+2+2 (starting from the end) >= 6.

If all the sums still not greater then the given number, I return (-1) to indicate that I can never reach the given number.

My Recursive function is as follows but I'm getting "Missing Return Statement" error. How can I solve thi problem for the given question.

    public static int findIt(int[] arr, int index, int min)
{
    if(index >=0)
    {
        int calc=0;
        int counter=0;
        for(int from = arr.length-1 ; from>=index; from--)
        {
            calc += arr[from];
            counter++;
        }
        if(calc>=min)
            return counter;
        else
            findIt(arr, --index, min);
    }
   else
    return -1;
}

Upvotes: 0

Views: 71

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

You're missing a return:

public static int findIt(int[] arr, int index, int min)
{
    if(index >=0)
    {
        int calc=0;
        int counter=0;
        for(int from = arr.length-1 ; from>=index; from--)
        {
            calc += arr[from];
            counter++;
        }
        if(calc>=min)
            return counter;
        else
            findIt(arr, --index, min); // <=== Here
    }
   else
    return -1;
}

Putting a return in front of findIt(arr, --index, min); will return the result of findIt.

If a function declares that it returns a value, all paths through the code must do so. And separately, for this function to work correctly, you really want to return the result of that recursive findIt call.

Upvotes: 0

SMA
SMA

Reputation: 37023

Instead of:

findIt(arr, --index, min);

Return the value from it like:

return findIt(arr, --index, min);

Upvotes: 2

pinoyyid
pinoyyid

Reputation: 22306

The missing return should be after the line findIt(arr, --index, min);

Upvotes: 0

Related Questions