2

I am using an recursive linear search algortihm. even the if condition is true it always returns null. If I don't put null it gives an error. I could not just figure out that how can I made proper. Thanks for help

private String findMinimumPricedHelper(String name, IMedia[] treeArray, int index) {
   if (some conditions) 
       return treeArray[index].toString();
   else
       findMinimumPricedHelper(name, treeArray, index+1);
   return null;
}

I was expecting a value treeArray[index].toString() but it returns null

3 Answers 3

4

You are ignoring the value of the recursive call. Try:

private String findMinimumPricedHelper(String name, IMedia[] treeArray, int index) {
    if (some conditions) {
        return treeArray[index].toString();
    } else {
        return findMinimumPricedHelper(name, treeArray, index+1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

As @Eran said, you're missing the return of the recursive call, but you should also consider the case where the condition is never true and you reach the end of the array. This will crash if the condition is never met.

Comments

1
  • You forget return answer from recursion call.
  • I recommend you check corner case when index larger than size of array.
  • If you want to make sure this method never crashes, you should handle index less than zero, treeArray is null.

So ideal code should be:

private String findMinimumPricedHelper(String name, IMedia[] treeArray, int index) throws IllegalArgumentException {
   if (treeArray == null || index < 0) throw new IllegalArgumentException("parameters are not correct");
   if (index >= treeArray.length) return null;
   if(some conditions) return treeArray[index].toString();
   return findMinimumPricedHelper(name, treeArray, index+1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.