0

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");
        }}
    }
}

}

  • Can you give an example of an input that doesn't give the expected output? – Eran Jan 19 '15 at 14:35
  • Recursion means: calling itself. Even though your isPalindrome calls checkPalindrome, which then again calls isPalindrome, this isn't really recursion. In order for it to be recursion, isPalindrome should call isPalindrome. checkPalindrome shouldn't exist. – Stultuske Jan 19 '15 at 14:36
  • possible duplicate of [Creating a recursive method for Palindrome](http://stackoverflow.com/questions/4367260/creating-a-recursive-method-for-palindrome) – roeygol Jan 19 '15 at 14:37
  • Thanks for the help. These are the changes I made. return checkPalindrome(y.substring(1, y.length()-1)); to is Palindrome in.next(); to in.nextLine(); Thanks again. – 10typesofpeople Jan 19 '15 at 15:03

2 Answers2

1

Scanner#next(), as per javadoc, Finds and returns the next complete token from this scanner i.e. a word (breaks on Space).

Scanner#nextLine() instead Advances this scanner past the current line and returns the input that was skipped meaning that gets all the line written (in your case until Enter is pressed).

Change in.next() to in.nextLine().

Narmer
  • 1,414
  • 7
  • 16
0

The problem is in RecursivePalindromeTester. The scanner you are using breaks on whitespace. You can change it to break on newline instead:

in.useDelimiter(new Pattern("\n");
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82