-1

Im practicing recursion for my own amusement using the codingBat exercises. Im doing this exercise:

Given a string, compute recursively the number of times lowercase "hi" appears in the string, however do not count "hi" that have an 'x' immedately before them.

countHi2("ahixhi") → 1
countHi2("ahibhi") → 2
countHi2("xhixhi") → 0

I tried to do this code but it keep throwing out of bounds exception:

public int countHi2(String str){    
    if(str.length()<2){
        return 0;
    }
    else if(str.substring(0,3).equals("xhi")){
        return countHi2(str.substring(3));
    }
    else if(str.substring(0,2).equals("hi")){
        return 1+countHi2(str.substring(2));
    }
    else{
        return countHi2(str.substring(1));
    }
}

I changed the substring() and equals to startsWith()

else if(str.startsWith("xhi")){
            return countHi2(str.substring(3));

And now works perfectly, can someone please point out why my first code wasnt correct? Is there a difference between startsWith() and equals()?

GrandMasterFlush
  • 6,269
  • 19
  • 81
  • 104
user2737948
  • 329
  • 2
  • 10
  • 25
  • 8
    Does your name start with `"user"`? Is it equal to `"notuser"`? – Sotirios Delimanolis Sep 15 '14 at 21:20
  • 1
    Before doing substring(0, 3), you should make sure that the string has at least 3 characters. That's what startsWith does fine and that your code doesn't. If you had read the stack trace of the exception, you would have notices that the exception wasn't throw by equals(), but by substring(). The exception stack trace also tells you at which line of code the exception is thrown. Not reading the stack trace is your biggest mistake. – JB Nizet Sep 15 '14 at 21:25
  • I'll just ask since you don't really specify, do you have to use `equals or startsWith` or is something like `contains` valid also because I'd say contains would be a bit easier and more robust for other examples of strings; this implementation seems to assume the test string is always in the pattern *hi*hi etc. – Culyx Sep 15 '14 at 21:30

1 Answers1

6

First you make sure the string has at least 2 characters in it, then you test if the first three characters are xhi. String.substr throws an exception if the string is not long enough.

String.startsWith doesn't have this problem, it doesn't throw an exception when you check whether a 2 character string starts with 3 characters - it just returns false.

zmbq
  • 38,013
  • 14
  • 101
  • 171