为什么使用 Character.isAlphabetic() 时我的字母字符没有添加到堆栈中?



我的代码,如果在粘贴中首选。

我正在为Java做家庭作业。基本上,该程序的重点是确定句子字符串是否是回文(并且它必须使用堆栈来完成此操作(。如果句子包含标点符号等,则应将其删除,即

"夫人,我是亚当"

将使用以下方法进行更改和比较:

"夫人"

所以这就是在测试它是否是回文之前要做的事情。我有另一个版本,适用于没有标点符号的单词,例如"眼睛"。

无论如何,我的代码的一部分导致我出现空堆栈异常 - 我相信这意味着我将字符串存储到的堆栈为空/它没有被存储(任务需要使用堆栈(。这只发生在我使用"isAlphabetic(("函数时。当我删除它时,它会返回 false,这在我的代码中更靠后。基本上我不明白为什么循环中检查字符串字符是否为字母的部分没有将字母值推送到堆栈上。似乎它没有推送任何东西,因此空堆栈异常。如果我删除该部分,它确实会推到堆栈上,但它返回 false(这是正确的,因为"e'ye"不会被视为回文,但我需要删除标点符号,以便它是一个回文并返回 true(。任何见解不胜感激,谢谢!

import java.util.LinkedList;
import java.util.Stack;
public class PalindromesSubmission {
/**
* Returns true if word is a palindrome, false if not
*/
public static void main(String[] args) {
//testing the function with different words
String word = "eye"; //true
String word2 = "Eye"; //true
String word3 = "no"; //false
String word4 = "e'ye"; //empty stack exception
String word5 = ""; //true
String word8 = "Madam, I'm Adam";
//System.out.println(isPalindromeSentence(word));
//System.out.println(isPalindromeSentence(word2));
//System.out.println(isPalindromeSentence(word3));
System.out.println(isPalindromeSentence(word4));
//System.out.println(isPalindromeSentence(word5));
//System.out.println(isPalindromeSentence(word6));
//System.out.println(isPalindromeSentence(word7));
//System.out.println(isPalindromeSentence(word8));
}
public static boolean isPalindromeSentence(String sentence) {
sentence = sentence.toLowerCase();
System.out.println(sentence); //for testing purposes
Stack<Character> first = new Stack<Character>();
for (int i = 0; i < sentence.length(); i++) {
if(Character.isAlphabetic(sentence.charAt(i))) {
first.push(sentence.charAt(i));
}
}
Stack<Character> firstCopy = new Stack<Character>();
firstCopy.addAll(first);
Stack<Character> second = new Stack<Character>();
for (int i = 0; i < sentence.length(); i++) {
second.push(first.pop());
}
for(int i = 0; i < firstCopy.size(); i++) {
//if firstCopy.first() == second.first() then pop both and continue. else return false.
char a = firstCopy.pop();
char b = second.pop();
if(a != b) {
return false;
}
}
return true;
};
}

您正在尝试从first中弹出sentence.length()字符:

for (int i = 0; i < sentence.length(); i++) {
second.push(first.pop());
}

但你不一定把那么多角色推到first上。 如果您的原始sentence中有一些非字母字符,您将少于sentence.length()个字符推到"第一个"上。

解决方案是从first开始弹出字符,直到first告诉您没有更多字符要弹出:

while (!first.isEmpty()) {
second.push(first.pop());
}

最新更新