I am being asked to write a recursive method to reverse a string. I have a class named Sentence with a private String variable named text. Program is run in separate main class by creating Sentence object and calling method. I can not change the return type of the method. I have been working on this for a while and getting nowhere. Any help or advice would be appreciated.
public void reverse() {
if (text.length() <= 1) {
return;
}
Sentence x = new Sentence(text.substring(1));
recur = text.substring(0, 1); //recur is another String variable I declared
text = x.text.concat(recur);
x.reverse();
}
You are pretty close. As far as I can see this should work if you swap these two lines:
Also, you should try to come up with meaningful variable names instead of
xandrecur. This will make it easier for others (and you!) to understand your code. For example: