Java 堆栈以确定字符串是否为回文

Java 堆栈以确定字符串是否为回文,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 pri

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

}
import java.util.Scanner;
/*/
此程序将读取字符串,如果字符串为
回文词、短语、句子或非回文词、短语、句子。如果单词不是回文
程序将打印为false,否则程序将打印为true。
*/
公共类回文演示
{
公共静态布尔值isAlindrome(字符串str)
{
布尔值isPal=true;
//创建堆栈
堆栈=新堆栈(str.length());
//将所有字符推入堆栈
对于(int i=0;i
我在
Stack Stack=new Stack(str.length());

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

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

Stack stack = new Stack();
除此之外,除了一些不好的做法外,您的程序似乎还在运行:

  • 您不应该使用原始类型。
    Stack
    ,而不是
    Stack
  • 根据,不再建议使用
    堆栈
    ,应改用
    Deque
    ArrayDeque
  • 当您可以简单地比较
    i
    -th和
    str.length()

查看API文档,特别是构造函数列表。注意没有接受参数的构造函数。建议您搜索“java找不到符号”。考虑使用泛型,即堆栈堆栈=新堆栈()。;然后堆栈只接受并返回字符,您可以摆脱讨厌的类型cast char c=(char)stack.pop()