我想讀一個字符串,但在此之前我推入堆棧,其排隊隊列我,我需要消除所有的空格和標點符號,同時維持秩序。我嘗試像這樣做,但它的表現和異常。我新來的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)
您發佈的誤差來自哪裏,你叫'Stack.pop'但在你的代碼貼出你永遠不會調用'pop'線。 –