1

I am creating a word-by-word palindrome ("yes I can, can I yes?") as follows: ''' public class Palindrome {

LinkedQueue<String> queue;
LinkStack<String> stack;

public Palindrome() {
    LinkedQueue<String> queue = new LinkedQueue<>();
    LinkStack<String> stack = new LinkStack<>();
}

public boolean isPalindrome(String sentence) {

    String[] sentenceSplit = sentence.split(" ");

    for(String word : sentenceSplit) {
        queue.enqueue(word.toLowerCase());
        stack.push(word.toLowerCase());
    }

    while (stack.top() == queue.front()){
            stack.pop();
            queue.dequeue();
    }

    if(stack.size() == 0) {
        return true;
    }
    return false;
}

public static void main(String[] args) {
    Palindrome test = new Palindrome();
    test.isPalindrome("can you you can");
}

} ''' In here, it says I receive a nullpointerexception during my for each loop where I enqueue and push each string in the string array, I have tested the strings in the string array and they do exist, so why am I receiving this error? Thanks.

2 Answers2

1

Change

LinkedQueue<String> queue = new LinkedQueue<>();
LinkStack<String> stack = new LinkStack<>();

to

queue = new LinkedQueue<String>();
stack = new LinkStack<String>();
seandon47
  • 286
  • 1
  • 6
0

You constructor is declaring variables but you use your class attributes that are not initialized. Move the content of your constructor into your class' attributes.

Also, you might want to use .equals instead of == when comparing Strings in "while (stack.top() == queue.front())".

Romano
  • 445
  • 1
  • 8
  • 20