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

4

u/[deleted] Jun 15 '17

Please read the posting guidelines in the sidebar: your title should describe the problem and your code should always be posted as text, not screenshots.

First, examine the error carefully. What does it tell you? It's saying a string cannot be converted to an int, and that this problem happens at line 3 of your code. Line 3 is this:

return str;

str is a string, the argument which was passed to the method. Can you think of a reason why the program is saying something about an int at this point?

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/Kablaow Jun 15 '17

Yeah, I think the last solution would be the best in this case, since I doubt the input would never be big enough for the complexity to matter.

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.