【发布时间】:2015-07-26 02:30:10
【问题描述】:
为什么我的代码应该返回 true,却返回 false?
如果 str2 包含零个或多个字符,然后是 str1 的所有字符,然后是零个或多个字符,则方法 isSubstring 应该返回 true。如果 a 没有出现在 b 中的任何位置,该方法应该返回 false。
我不是在寻找返回正确输出的替代方法,而是想找出我的代码错误的原因。
public class stringRecursionPractice{
public static void main(String[] args){
String str1 = "abc";
String str2 = "abc";
System.out.println(isSubstring(str1, str2));
}
/*
* Returns the string containing only the first character of the
* specified string.
*/
public static String head(String s) {
return s.substring(0, 1);
}
/*
* Returns the string containing the all the characters but the first
* character in the specified string.
*/
public static String tail(String s) {
return s.substring(1);
}
public static boolean isSubstring(String str1, String str2){
if(str1.length() == 1 && str1.charAt(0) == str2.charAt(0)){
return true;
}
if(head(str1).equals(head(str2))){
isSubstring(tail(str1), tail(str2));
}
return false;
}
}
【问题讨论】:
-
你应该做一些调试。
-
你已经做了什么来调试你的代码?
-
我试了几次调试,总是返回false。
-
第二个
if block, should also contains somereturn`语句,因为没有那个,控制总是转到最后一个return false;。 -
但是最后一次递归调用 isSubstring("c", "c") 不会返回 true 吗?