我在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));
    }

}

最佳答案

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


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

import java.util.Stack;


然后,您将遇到另一个错误,因为Stack仅具有无参数的构造函数,因此无法像代码中那样接受int参数。解决方法是简单地删除参数:

Stack stack = new Stack();


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


您不应该使用原始类型。代替StackStack<Character>会更好
根据javadoc,不再建议使用Stack,而应使用DequeArrayDeque
当您只需要比较第i个字母和第str.length() - i - 1个字母时,堆栈对于此任务来说实在是太过分了,使用过多的额外存储空间

09-05 00:45
查看更多