2
public static boolean work(String str, char ch)  

Use recursion to find out if str contains at least one occurrence of ch.
Return true if it does and false if not.
Example

work("whynot", 'n') returns true
work("please", 'z') returns false

public static boolean work(String str, char ch){
    //base case 
    if (str == null || str.equals("")){
        return false; 
    }

    //recursive case
    if (ch == str.charAt(0)){
        return true; 
    }else {
        work(str.substring(1), ch); 
    }
    return false; 
}

My code will correctly return "true" when ch is the first character of str, but return an incorrect answer of "false" when ch is in any other part of the str.

Please explain why... I was thinking it was because my last "return false;" statement overrode the "true" from the recursive case if, but when I get rid of the last "return false;" my compiler will complain that I'm missing a return value.

2
  • Why are you calling contains(str.substring(1), ch); instead of work? Commented Jul 12, 2015 at 22:13
  • You keep changing the name of you function (should be "work", but was "contains", now it's "work", but you're calling "contains" inside...) clean that up Commented Jul 12, 2015 at 22:17

1 Answer 1

2

That's because you're not returning the result of the recursive call.

Try this:

public static boolean work(String str, char ch){
    //base case 
    if (str == null || str.equals("")){
        return false; 
    }

    //recursive case
    if (ch == str.charAt(0)){
        return true; 
    }else {
        return work(str.substring(1), ch); 
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks so much, that worked. However, is it true that my last return false statement can override the true from the if statement above?
Not now that the code is fixed. There's no further processing after a return code (set exception handling aside), and if both branches of an if statement end in a return, that's as far as it goes. (P.S. - You like the answer? accept it! :-)
Yes I will, but the site won't let me until 10 mins has passed. Thank you so much.
Think about it for a second. If the function "work" returns true, then if you do not return this what will happen? The else statement will end and it will return false - even if the inner call returned true.
This looks like an exercise problem to try understand exactly this kind of behavior :)
|

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.