我正在读取一个字符串,但在将其推入堆栈并将其排入队列之前,我需要在保持顺序的同时消除所有空格和标点符号。
我是 Java 新手,并尝试了以下引发异常的代码:
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++;
}
}
输出:
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)