I am doing a problem from codingbat and I am stuck at this problem. The question asks me to find all the 'hi' in the string but ignore the 'hi' which have 'x' just before them. In other words, don’t count 'xhi' but only 'hi'.
Every input works fine in my code except for when the input is "xxxx".
My code is as follows:
public int countHi2(String str) {
String s = "hi";
int count = 0;
if(str.length() < 2) {
return 0;
}
else if(str.charAt(0) == 'x' && str.substring(1,3).equals(s)) {
count+= countHi2(str.substring(3));
}
else if(str.substring(0,2).equals(s)){
count+= 1 + countHi2(str.substring(2));
}
else {
count+= countHi2(str.substring(1));
}
return count;
}
The problem is that it throws IndexOutOfBoundsException. The link to the question can be found here.
You see an exception because
substringthrowsIndexOutOfBoundsExceptionif the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. You check for the length to be at least 2, and then dosubstring(1, 3), causing an exception.You can avoid the problem with
IndexOutOfBoundsExceptioninsubstringby switching tostartsWithAPI, which does not throw exceptions even when you compare your string to a longer one.