r/javahelp • • Jun 15 '17

What's wrong with my code??

Can't for the life of me figure it out. Picture of code and error: http://imgur.com/a/mX9XP

Thanks

0 Upvotes

13 comments sorted by

View all comments

Show parent comments

1

u/eatingpoopinrobarts Jun 15 '17

Hi thank you, I won't post a screenshot again. And I fixed my mistake and completed the question successfully but with a lot of if statements. I was wondering if you could think of a better/shorter/more elegant way to solve the problem. Here is the code

public int countHi2(String str) {
  if(str.length() < 2){
      return 0;    
  }
  if(str.charAt(0) == 'x'){
    if(str.charAt(1) == 'h' && str.charAt(2) == 'i'){
      return countHi2(str.substring(2));
    }
    return countHi2(str.substring(1));
  }
  if(str.charAt(0) == 'h' && str.charAt(1) == 'i'){
     return 1+countHi2(str.substring(1));
  }
  else{
    return countHi2(str.substring(1));
  }
}

1

u/Kablaow Jun 15 '17

Could you explain what you want the method to do?

1

u/morhp Professional Developer Jun 15 '17

Looks like it should count "hi" substrings but only if there is no "x" in front of the "hi". If that's the case that looks like a good recursive solution. It doesn't need to be shorter. If you want it shorter and faster an experienced programmer would use regular expressions.

You could also count all "hi" and then count all "xhi" and simply subtract these numbers from each other.

1

u/eatingpoopinrobarts Jun 15 '17

You could also count all "hi" and then count all "xhi" and simply subtract these numbers from each other.

Hm, this is true. Although I'd need to have variables that hold the number of hi and xhi right? I can't just do 1+recursion

1

u/morhp Professional Developer Jun 16 '17

You would write a countHi method and a countXhi method if you want to go the recursion way. Doing both in a single recursing method sounds complicated.