java - Using recursion to find the number of 'hi' in a string but not 'xhi' -
i doing problem codingbat , stuck @ problem. question asks me find 'hi' in string ignore 'hi' have 'x' before them. in other words, don't count 'xhi' 'hi'.
every input works fine in code except when input "xxxx". code 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 throws indexoutofboundsexception. link question can found here.
you see exception because substring throws indexoutofboundsexception if beginindex negative, or endindex larger length of string object, or beginindex larger endindex. check length @ least 2, , substring(1, 3), causing exception.
you can avoid problem indexoutofboundsexception in substring switching startswith api, not throw exceptions when compare string longer one.
Comments
Post a Comment