0

Beginner CS student here. I'm working on a Palindrome checker for a class and this is entirely functional if not for the required Uppercasing in the main method. How could I made my isPalindromeRecursive method ignore the string case?

I need to figure out how to make a case-insensitive method. Also I have to have both a isPalindromeRecursive and isPalindromeIterative method and I don't understand the difference if someone could explain.

public class PalindromeDetector {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        int count = 2;
        for(int i = 0; i < count; i++ ) {

            System.out.println("Enter a name.");
            String name = keyboard.nextLine();

            // I wanted to experiment with the new String tools we learned so my capitalization is strange.
            String cap = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
            System.out.println(cap);

            if(isPalindromeRecursive(cap))
                System.out.println(cap + " is a palindrome.");
            else
                System.out.println(cap + " is not a palindrome.");

            count++;
        }

    }

    public static boolean isPalindromeRecursive(String s) {
            if(s.length()==0 || s.length() ==1) {
                return true;
            }
            if(s.charAt(0) == s.charAt(s.length()-1)) {
                return isPalindromeRecursive(s.substring(1, s.length()-1));
            }
                return false;
    }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [Check string for palindrome](https://stackoverflow.com/questions/4138827/check-string-for-palindrome) – dawis11 Apr 22 '20 at 18:21
  • You can use substring method instead of charAt and compare the single character string with java.lang.String.equalsIgnoreCase – David SK Apr 22 '20 at 18:31

1 Answers1

0

You could look at using the Character.toUpperCase() method to compare chars in a case insensitive way.

You're also creating a lot of String objects, which isn't really necessary.

Putting the two together you have something like this:

public static boolean isPalindromeRecursive(String s, int front, int back) 
{
  if(front >= back) {
      return true;
  }

  if(Character.toUpperCase(s.charAt(front)) == Character.toUpperCase(s.charAt(back))) {
      return isPalindromeRecursive(s, front+1, back-1);
  }
  return false;
}

Which you'd call via:

for(String s : new String[] {"", "a", "ab", "aa", "aA", "aba", "abA", "abc"})
    System.out.format("%s:%b%n", s, isPalindromeRecursive(s, 0, s.length()-1));

Output:

:true
a:true
ab:false
aa:true
aA:true
aba:true
abA:true
abc:false
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16