0

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.");
        }
    }
}
  • 2
    This sounds like a great opportunity to familiarize yourself with the use of a debugger. While debugging, when you step through the code line by line and observe the behavior and values, at what point does the logic deviate from what you expect? – David Mar 04 '17 at 18:23
  • 2
    I think the error come from `i++` in `do` loop. You increase before get value of character. – Manh Le Mar 04 '17 at 18:25
  • I think @Bathsheba's got the main problem, but also you probably want to increment your counters at the end of the loop - you're not checking the first character, but you *will* check the first pair where `j>i` fails before the loop exits. – hugh Mar 04 '17 at 18:27
  • Possible duplicate of [Check string for palindrome](http://stackoverflow.com/questions/4138827/check-string-for-palindrome) – azro Mar 04 '17 at 18:28
  • Hi @David, how can I go by that? At the moment I'm just using Atom and a Terminal, nothing fancy like an IDE. – Beauregard Lionett Mar 04 '17 at 18:33

5 Answers5

4

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

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);
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

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.

B. Witter
  • 564
  • 6
  • 19
1

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!

zsmb13
  • 85,752
  • 11
  • 221
  • 226
0

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.

Sander Vanhove
  • 995
  • 4
  • 11