
Paul W. answered 10/10/21
Professional Web Software Developer with Passion for Teaching
First off, let's get some "boiler plate" code out of the way. We need to prompt the user for some input, read a string that they type in, call the function that we need to implement, and display the results:
Now that the boiler plate is out of the way, let's discuss the important part: the implementation of the "containsTwoInARow" function. Because you are instructed to implement this as a recursive function, you need to think about how to break it down into a finite set of simple cases, where in one case you can quickly and trivially say "yes, this string contains two of the same letter in a row," in another cases you can say "no, this string definitely does not contain two letters in a row," and in a third case you can turn the problem into a slightly simpler case by reducing the amount of data to process (either by dividing it in two parts, or by reducing the amount of data by a fix amount).
The simplest possible case where we can say "yes, this string contains two of the same letter in a row" would be the case where the first and second letter are the same.
The simplest possible case where we can say "no, this string definitely does not contain two letters in a row" would be the case where the string contains only one character (or zero for that matter).
In any other case we can skip the first character (since we've already checked, and it is not the same as the second character), and check again (recursively) starting at the second letter of the string 🤯. We do this by calling the same function again (that's what recursion is), only with a substring starting at position 1 (strings in Java are index by 0).
So what does this look like in Java?
The length is less than or equal to one case (it's best to check this first, because it simplifies to other checks):
The first two letters are the same case:
And the recursive call:
I hope this was instructive in helping you understand recursion.
-----
Please don't use Wyzant as a way to get quick answers to your homework assignments. If there's a concept you are struggling with, phrase your question as a request for an explanation of that concept. If you just use it to get homework answers, you will receive no real benefit and wind up failing in the long run.