Beauregard Lionett
Beauregard Lionett

Reputation: 321

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:

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

Upvotes: 0

Views: 562

Answers (5)

Sander Vanhove
Sander Vanhove

Reputation: 1115

Well, the problem is that you set your isPalindrome every time you check two letters. So when the last 2 letters checkt are the same, it will say it is a palindrome. Instead try this:

import java.util.Scanner;

public class Main
{
    public static void main (String[] args)
    {
        boolean isPalindrome = true;
        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() - 1;

        while(i < j && isPalindrome) {

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

            if (array[i] != reverseArray[j])
                isPalindrome = false;

            i++;
            j--;

        }

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

So now the isPalindrome boolean is set to true in the beginning, and when we find something that contradicts this (two characters that are not the same) it will set isPalindrome to false.

I have not tested this code, so there could be some other error. But this is the one I saw at first glance.

EDIT: i didn't start from the beginning of the string. And best to use a while instead of do while because the string could be empty.

Upvotes: 0

zsmb13
zsmb13

Reputation: 89548

A couple things.

  • You should do your index changes at the end of your loop, to fix starting the lower index from 1.
  • With the previous change, you should start your upper index from userInput.length()-1 as that will then be the first index from the top that you check.
  • You should stop when you find one mismatch, as otherwise with a string of odd length, your result will always be the check of the middle character against itself (and otherwise your result will end up being the check of the two middle characters of an even string against each other).

If you'd like the full re-worked solution, I can post it, but you can probably fix it yourself from here!

Upvotes: 1

B. Witter
B. Witter

Reputation: 644

Are you allowed to use StringBuilder? If so, you can do String reverseText = new StringBuilder(userInput).reverse().toString();

If not, why not try iterating through the array once and then compare at the end? Leave your array and reverseArray initializers as they are, but then do a for or while loop after that just faithfully copies from the userInput variable into the correct locations in both the arrays.

Then you can just use a single comparison at the end to decide what to print.

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234705

Once you've established that the input is not a palindrome, you should end the test.

Currently your algorithm is allowed to change its mind!

You are also incrementing i prematurely.

Upvotes: 4

Related Questions