简体   繁体   中英

Java Beginner Recursion with boolean

I don't understand why I am getting "return statement missing".

Here is the image with the code:
在此处输入图片说明

In your 2nd and 3rd if conditions there are no returns. Instead of your else, just return false.

So it reads:

    public class isTrans {
        public static boolean isTrans(String s,String t) {
            if (t.length()==1 && (s.charAt(s.length()-1))==t.charAt(0)){
                return true;
            } else if (s.charAt(0)==t.charAt(0)){
                return isTrans(s,t.substring(1));
            } else if (s.charAt(1)==t.charAt(1)){
                return isTrans(s,t.substring(1), t);
            }
            return false;
        }
    }

在这种情况下,您必须在所有条件下返回或在方法结束时返回。

if(/*...*/) {
    return true;
}
else if(/*...*/) {
    return isTrans(/*...*/); // return whatever isTrans returns
}
else if(/*...*/) {
    return isTrans(/*...*/); // here too
}
else {
    return false;
}

You have to return the result of the function execution in your else if , so the recursion works properly. Like this:

return isTrans(s, t.substring(1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM