1

I am trying to build a Palindrome finder class that uses an ArrayStack of characters to find palindromes in any word or phrase passed to it. However, when I pass a palindrome as a string to my code, it returns false.

I have debugged my code several times and even wrote the program over, but I cannot figure out why my code isn't working properly. I think it may be something simple that I am overlooking in the isPalindrome() method, the constructor or instance variables.

public class PalindromeFinder {
    ArrayStack<Character> charStack = new ArrayStack<>();
    String strVerify = "";
    private String strCheck;

    public PalindromeFinder(String strCheck) {
        strCheck = strCheck.toLowerCase();
        pushStr(strCheck);
        strVerify = popStr();
    }

    public void pushStr(String strToPush) {
        for (int chVal = 0; chVal <strToPush.length(); ++chVal) {
            char ch = strToPush.charAt(chVal);
            ch = Character.toLowerCase(ch);
            if (Character.isAlphabetic(chVal)) {
                charStack.push(ch);
            }
        }
    }

    public String popStr() {
        while (!charStack.empty()) {
            strVerify += charStack.pop();
        }
        return strVerify;
    }

    public boolean isPalindrome() {
        return strVerify == strCheck;
    }
}

The following lines of code return false in the main method of my program:

PalindromeFinder p = new PalindromeFinder("mom"); System.out.println(p.isPalindrome());

Any help or improvements on my code would be greatly appreciated.

kof_
  • 13
  • 3

2 Answers2

1

In the PalindromeFinder constructor you never assign the strCheck parameter to the strCheck field, so when you compare the field in isPalindrome, it still has its default value, null. You need this line in the constructor:

this.strCheck = strCheck;

Consider declaring the field as final:

private final String strCheck;

This has a few small benefits for fields like this that do not change after construction. One of those benefits is that the compiler will yell at you if any constructor forgets to initialize the field, so it would have caught this error and saved the confusion.

You also need to do the later string comparison with equals, not ==:

return strVerify.equals(strCheck);

P.S. PalindromeFinder does not really need to be a class. It would be simpler as a single static utility method isPalindrome(String s), but anyhoo.

Boann
  • 48,794
  • 16
  • 117
  • 146
  • I solved it myself. Thanks. I changed the if statement in the pushStr() method. How would I make this a single static utility method while using ArrayStacks? – kof_ Oct 30 '15 at 04:04
  • @kof_ There's no trick to it; just put the palindrome code in one method. – Boann Oct 30 '15 at 11:34
0

You have to compare strings in Java with the equals() method.

your method isPalindrome should be like that:

public boolean isPalindrome() {
    return strVerify.equals(strCheck);
}
Coder55
  • 559
  • 5
  • 17