java - 为什么我的代码会跳过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
解决方案
您没有使用递归调用返回的布尔值,因此如果第一个计算结果为 ,则find(...)
您的函数当前始终返回。在适当的时候需要返回一个额外的基本情况:false
if
false
false
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);
}
}
推荐阅读
- mysql - 计算得分高于平均分的男性和女性
- c# - 使用泛型方法的目的,其中泛型是一些基类
- perl - Perl CGI::Session 开始问题
- python-3.x - 连接拒绝远程运行在 Docker 容器上的 Spark Master
- reactjs - 为什么 hls.js 库会导致视频质量下降,而原生 Apple 流媒体库运行良好?
- adobe - INVALID_X_API_USER_HEADER
- java - 如何在房间数据库中将列名作为参数传递?
- php - laravel 不更新数据,只刷新
- node.js - 具有 _id 关系的类型的最后一个值
- php - 循环时检查数组的先前元素