dj5 dj5 - 29 days ago 25
Java Question

Determining a Palindrome using Stack and Queue in java

Here I am trying to determine if a word or phrase is a palindrome by using stacks and queues depending on the phrase I write in.

What it is doing is that it says that everything is a palindrome and writes "Palindrome" by how many letters it has.

I'm guessing that I need to add something between the last for loop and the while loop, but I'm not sure what.

public class CheckPalindrome {

public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

while (true) {

String line = reader.readLine();


if (line.toLowerCase().equals("quit")) {
break;
}

Stack<Character> stack = new Stack<Character>();

Queue<Character> queue = new LinkedList<Character>();

for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}

for (int i = line.length() - 1; i >= 0; i--) {
queue.add(line.charAt(i));
}

while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}

}
}
}

Answer

I made some very minor modifications (first to fix one of your for loops, and second to prevent your "Palindrome/Not a Palindrome" message from printing once for every character in the input) to your code to get it to work:

import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
class Palindrome {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {

            String line = reader.readLine();


            if (line.toLowerCase().equals("quit")) {
                break;
            }

            Stack<Character> stack = new Stack<Character>();

            Queue<Character> queue = new LinkedList<Character>();

            for (int i = 0; i < line.length(); i++) {
                stack.push(line.charAt(i));
            }

            for (int i = 0; i < line.length(); i++) {
                queue.add(line.charAt(i));
            }

            boolean isPalindrome=true;
            while (!queue.isEmpty()) {
                if (queue.remove().equals(stack.pop())) {
                    continue;
                } else {
                    isPalindrome=false;
                    break;
                }
            }
            if (!isPalindrome) {
                System.out.println("Not a Palindrome");
            } else {
                System.out.println("Palindrome");
            }

        }     
    }
}
Comments