I’m reading a string but before it’s pushed in the stack and enqueued it in queue I need to eliminate all spaces and punctuation while maintaining the order.
I am new to Java and have tried below code which throws exception:
for (int i = 0;i < input.length(); i++){
String character = Character.toString(input.charAt(i));
if (charChecker(character)){
stack.push(character);
queue.enqueue(character);
}
}
private static boolean charChecker (String character) {
if (character.equals(" ") || character.equals(".") ||
character.equals("?") || character.equals("!") ||
character.equals(",") || character.equals(";") ||
character.equals(":") || character.equals("-"))
return false;
else
return true;
}
int diff = 0;
for (int i = 0; i < input.length(); i++) {
String char1 = stack.pop();
String char2 = queue.dequeue();
if (!(char1.equalsIgnoreCase(char2))) {
diff++;
}
}
Output:
Enter file name: input1.txt
evil live
Exception in thread "main" java.util.EmptyStackException
at Stack.pop(Stack.java:22)
at Palindrome.main(Palindrome.java:57)
The problem is you are popping the wrong amount of times.
You do not put
input.legnth()number of characters on the stack, but are calling pop() that many times. This is because you do not place the white-space and punctuation characters onto the stack.Try using: