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

时间:2017-08-19 03:48:56

标签: java stack

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

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

“女士,我是亚当”

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

“madamimadam”

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

无论如何,我的代码的一部分导致我一个空堆栈异常 - 我相信这意味着我存储字符串的堆栈是空的/它没有被存储(任务需要使用堆栈)。这只发生在我使用“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;

    };

}

1 个答案:

答案 0 :(得分:2)

您尝试从sentence.length()

中弹出first个字符
 for (int i = 0; i < sentence.length(); i++) {
        second.push(first.pop());
    }

但你并不一定会将那么多字符推到first上。如果您的原始sentence中有一些非字母字符,则会将少于 sentence.length()个字符推送到“first”。

解决方案是从first中弹出字符,直到first告诉您没有其他字符可供弹出:

 while (!first.isEmpty()) {
        second.push(first.pop());
    }
相关问题