Search code examples
javapalindromestack-overflow

Having trouble with terminating code on a recessive palindrome method


I'm trying to write code that tells the user if a word they input is a palindrome or not.

I am using a recursive method to reverse the word, but it isn't terminating correctly. The StackOverFlowError appears when I test it out. My terminating code looks correct to me, so I'm not sure why it isn't working.

Also, when I try to make the String object all lower case characters, does the debugger show that the word was made all lower case, or does it just stay the same?

Here is the code:

public class Palindrome
{
private String word;

/**
 * Constructor for objects of class PalindromeTester
 */
public Palindrome(String supposedPalindrome)
{
    word = supposedPalindrome;
}

/**
 * Tests if the word is a palindrome or not.
 */
public void testPalindrome()
{
    String reversed = reverse();
    if(reversed.equals(word.toLowerCase()))
    {
        System.out.println(word + " is a palindrome!");
    }
    else
    {
        System.out.println(word + " is not a palindrome.");
    }    
}

/**
 * Reverses the word.
 * 
 * @return the reversed string.
 */
private String reverse()
{
    return reverseHelper(word);
}

/**
 * A recursive method that reverses the String for the
 * reverse the string method.
 * 
 * @return the reversed string.
 */
private String reverseHelper(String s)
{
    s.toLowerCase();
    if(s.length() <= 1)
    {
        return s;
    }
    else
    {
        return reverseHelper(s.substring(1, s.length()) + s.charAt(0));
    }
}
}

Thank you for your help!


Solution

  • two mistakes in your code:

    1. String are immutable
      so doing s.toLowerCase() won't make any changes to s, you need to assign in back to an String
      s = s.toLowerCase();

    2. Your recursive method is buggy
      return reverseHelper(s.substring(1, s.length()) + s.charAt(0));
      it always passes String of length s.length() (I mean if String s is of length 5 then you recursive call is always passing string of length 5 only with only position of characters being changed)

    Suggestion:

    1. make you recursive call to shorten you string each time so that it finally matches if condition after string has been reversed
    2. Or use StringBuilder#reverse() method to reverse your string