First of all this is not homework. Just me practicing. I'm trying to recursively determine the number of times "hi" appears in the given string, but in every case it skips to the last else if statement and things the string is empty. Any ideas?
Basically, if(string starts with "hi") increment count by 1 and recurse with the string after the 2nd index to skip over the "hi" it just counted
else if(string does not start with "hi" and string is not empty) recurse with the string after its 1st index to see if it starts with "hi" the next time around.
else if(string is empty) Print("End of text reached") return count;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
counteris part of the external call. At minimum, this should be madeprivate, with apublicwrapper that does not containcounter(and is not recursive). The other method is to do the addition during the recursive return. Also, you're checking withstartsWith, then moving a cursor by 1 - what's wrong withindexOf(better optimization available there, I think).