Palindrome测试员在Java中使用堆栈和队列应用程序问题

问题描述 投票:0回答:2

我创建了一个应用程序来测试给定的输入字符串是否是回文。但是该程序无法检测到真正的回文,仅在任何时候返回false。我真的不知道为什么该方法不起作用。有人可以给我一些建议吗?谢谢。

public boolean palindromeTest()
{   
    // checks if the top of stack and the head of queue is the same for all elements
    // if not, breaks the while loop and returns false
    while (!queue.isEmpty())
    {
        if (stack.peek() != queue.first())
        {
            return false;
        }
        else 
        {
            queue.dequeue();
            stack.pop();
        }
    }

    return true;
}

}

java palindrome
2个回答
0
投票

这看起来错了

if (stack.peek() != queue.first())

您正在尝试比较两个字符串。但是,您的代码仅检查字符串是否为same object

if (!stack.peek().equals(queue.first()))

0
投票

将字符串与!=进行比较在Java中不起作用。 !=检查比较的两个对象是否实际上是同一对象。因此,您需要使用equals

检查
if (!stack.peek().equals(queue.first()))

除此之外,这似乎是检查字符串是否为回文的一种非常复杂的方法。从根本上讲回文词是向后读与向前读相同的单词。因此,您只需反转输入字符串并将反转的输入字符串与原始输入字符串进行比较即可轻松解决此问题。

public static void main(String[] args)
{
    //initiates a user input string 
    System.out.println("Enter a string to check: ");
    Scanner input = new Scanner(System.in);
    String palin = input.nextLine();

    //removes blank spaces in the input string
    palin = palin.replaceAll("\\s+","");

    // reverse the string
    String reverse = new StringBuilder(palin).reverse().toString();

    if (palin.equals(reverse)) { 
        System.out.println("Given string is a palindrome."); 
    }
    else {
        System.out.println("Given string is not a palindrome.");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.