Java – recursive method: why do I need a return statement?

Just to practice recursion, I wrote a classic introduction to recursion - a function that checks whether a given string is a palindrome

My question is: in the first if statement, why do I have to write to return palchecker (...) instead of just palchecker (...)? In my opinion, the function should not have the first return statement But from the test, I know it's not true, but I don't know why

(by the way, the printed statements are right there, so I can see what happens during the test. I like to see each execution line.)

public static boolean palChecker(String s){
    if ( s.charAt(0)==s.charAt(s.length()-1) && s.length()>1){
        System.out.println(s);
        return palChecker(s.substring(1,s.length()-1)); //why do i need the return here?
    }
    else if (s.length()==1 || s.length()==0){
        System.out.println(s);
        return true;
    }
    return false;
}

Solution

You need to return the final value returned by palchecker

The definition of a Java function is that it always returns a value... Even if it is the deepest chain in recursion, and finally brings true or false to the top

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>