I am trying to write a recursive method for determining if a string is palindromic. I have the code as follows:
String S = "radar";
int left = 0;
int right = S.length()-1;
public static void palindrome (int left, int right)
if (left < right || left==right)
palindrome (left+1, right-1);
I tried setting the return type to boolean, in order to indicate if the string is palindromic, but the method kept returning true (regardless). Recursion is such
a hard concept to grasp, can someone add some code to this method so it would return true depending on whether the string is palindromic, and hence
be able to print using println method?
Java Ranch isn't a code mill, so don't expect someone to just fill in the answer for you. That said, I'm not sure recursion is the best technique for finding the solution. Is this an assignment, or are you just trying to figure this out? Also, there is a really simple way of finding palindromes that involves using StringBuilder.
Joined: Jan 17, 2010
I don't come to Java Ranch to get my assignments done. I am doing this problem just out of curiosity and trying to reinforce the concept of Recursion, a concept that I find difficult to understand. Hence, I specifically decided to do this problem using recursion, but eventually lost my patience trying to figure out the solution.
I think you need to try to look at from a different point of view: I think I have an approach to the problem that uses recursion and is a little easier than what you are trying.
A palindrome is a word that is the same forwards as backwards right? So you can use a recursive method to reverse the string. Then you just have to use the String class methods to see if the Strings are equal; if they are then it's a palindrome, otherwise it isn't.
Hope this helps,
"If the facts don't fit the theory, get new facts" --Albert Einstein
The most important thing to remember when you are writing a recursive method is that it must always look like this:
In other words, you must always test for the case where the recursion should stop, and do something special if it should. In your first method, the recursion should stop if "left" and "right" refer to adjacent letters, right? If they do, then if they're equal, then the two-letter word is a palindrome; if they're not, then it's not. For a longer String, if the letters are equal, you have to call the method recursively; if they're unequal, then you can return false.