Search code examples
javacharpalindrome

Palindrome Recognizer


I'm learning Java. I'm building this Palindrome recognizer and using two arrays with chars, I think I got a good implementation with other things I've found around but I'm breaking my head to understand why it's not working as intended so far. What is happening:

  • "A Santa at Nasa", palindrome, checks as a palindrome.
  • "I don't know, anything", not a palindrome, checks as not a palindrome.
  • "Not a palindrome", not a palindrome, checks as a palindrome.

I basically need some help to understand where exactly I got it wrong on my code. Thanks!

/*
    "A Santa at Nasa" is an example of palindrome.
*/

import java.util.Scanner;

public class Palindrome
{
    public static void main (String[] args)
    {
        boolean isPalindrome = false;
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter a string:");
        String userInput = kb.nextLine();
        userInput = userInput.trim().replaceAll(" ", "").toLowerCase();
        char[] array = new char[userInput.length()];
        char[] reverseArray = new char[userInput.length()];
        int i = 0;
        int j = userInput.length();

        do {
            i++;
            j--;

            array[i] = userInput.charAt(i);
            reverseArray[j] = userInput.charAt(j);

            if (array[i] != reverseArray[j])
            {
                isPalindrome = false;
            }
            else
            {
                isPalindrome = true;
            }

        } while (j > i);

        if(isPalindrome)
        {
            System.out.println("It's a palindrome.");
        }
        else
        {
            System.out.println("Not a palindrome.");
        }
    }
}

Solution

  • Here's the problem, you must start before the first element of the input array, because you do a i++ at the beginning of your loop:

    int i = -1;
    

    Also, the exit condition of your loop can be improved, so it exits earlier:

    while (j > i && !isPalindrome);