有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于确定字符串是否为回文的java堆栈

我发现在Stack stack = new Stack(str.length());上找不到符号错误

为什么这不起作用

import java.util.Scanner;
/*/
    This progrma will read string and return if the string is 
    palindrome word, phrase, sentence or not. if the word is not palindrome
    the progrma will pritn out false otherwise the progrma will print out true. 
*/

public class PalindromeDemo 
{

    public static boolean isPalindrome(String str)
    {
        boolean isPal = true;
        //creating stack
       Stack stack = new Stack(str.length());
        //push all character into stack
        for(int i=0; i<str.length(); i++)
        {
            stack.push(str.charAt(i));
        }

        // now traverse str and check current character with top of stack
        for(int i=0; i<str.length(); i++)
        {
            char c = (char) stack.pop();
            // if not equal, break
            if(Character.toLowerCase(c) != Character.toLowerCase(str.charAt(i)))
            {
                isPal = false;
                break;
            }
        }
        return isPal;
    }

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String str;
        System.out.println("Enter a string: ");
        str = sc.nextLine();

        System.out.println(isPalindrome(str));
    }

}

共 (1) 个答案

  1. # 1 楼答案

    I'm getting cannot find symbol error on Stack stack = new Stack(str.length());

    似乎您忘记了Stack的导入语句:

    import java.util.Stack;
    

    然后会出现另一个错误,因为Stack只有一个无参数构造函数,它不能像代码中那样接受int参数。解决方法是简单地删除参数:

    Stack stack = new Stack();
    

    除此之外,除了一些不好的做法外,你的程序似乎还在运行:

    • 你不应该使用原始类型。而不是StackStack<Character>会更好
    • 根据javadoc,不再推荐Stack,您应该使用DequeArrayDeque
    • 当你可以简单地比较第i-th和第str.length() - i - 1-th个字母时,堆栈对于这项任务来说真的是太浪费了,占用了太多额外的存储空间