I am using recursion to find out whether a string is a palindrome, while ignoring spaces and non letter characters. However, each space causes the string to be split and tested separately. Here is my code.
public class RecursivePalindrome
{
RecursivePalindrome()
{
}
public boolean checkPalindrome(String y)
{
String s = y;
String removed = s.replaceAll("\\W", "");
removed = removed.toLowerCase();
return isPalindrome(removed);
}
public boolean isPalindrome(String y)
{
if ( y.length() < 2 )
return true;
char firstChar = y.charAt(0);
char lastChar = y.charAt(y.length() - 1);
if(firstChar != lastChar)
return false;
else
return checkPalindrome(y.substring(1, y.length()-1));
}
}
This is the tester class.
import java.util.Scanner;
public class RecursivePalindromeTester
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
RecursivePalindrome aMethod = new RecursivePalindrome();
int z = 0;
while (z < 1)
{
System.out.println("Please enter a word or phrase.(Entering q will stop the program)");
String n = in.next();
if(n.equalsIgnoreCase("Q"))
{
System.out.println("End of Program");
z++;
}
else{
if (aMethod.checkPalindrome(n))
{
System.out.println(n + " is a palindrome");
}
else
{
System.out.println(n + " is not a palindrome");
}}
}
}
}