Why does my code which should return true, return false?
The method isSubstring should return true if str2 contains zero or more characters, then all the characters of str1, then zero or more characters. The method should return false if a does not appear anywhere in b.
I am not looking for an alternative way to return correct output, but want to find out why my code is wrong.
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;
}
}
if block, should also contains somereturn` statement, since in the absence of that, the control always goes to the lastreturn false;.