首页 > 解决方案 > 为什么我的代码会跳过if语句中的return语句,然后执行else语句体?

问题描述

当我使用测试用例 find("mississippi", "sip") 运行我的代码时,它会在下面打印出“sippi”然后是“false”。我对此感到困惑,因为我假设“真实”会被打印出来。

我尝试删除 if 正文中的 return 语句,但出现错误

public static boolean find (String text, String str) //method to find "str" within "text"
    {
        if (text.substring(0, str.length()).equals(str))
        {
            System.out.println(text);
            return true;
        }
        else
        {
            text = text.substring(1);
            find(text, str);
            System.out.println(text);
            return false;
        }
    }

我希望输出为 sippi true,但实际输出为 sippi false

标签: javareturn

解决方案


您没有使用递归调用返回的布尔值,因此如果第一个计算结果为 ,则find(...)您的函数当前始终返回。在适当的时候需要返回一个额外的基本情况:falseiffalsefalse

public static boolean find (String text, String str) {
    if (text.length() < str.length()) { return false; }

    if (text.substring(0, str.length()).equals(str))
    {
        return true;
    }
    else
    {
        text = text.substring(1);
        return find(text, str);
    }
}

推荐阅读