java - 带递归的回文检查器?

标签 java recursion

我正在制作一个java程序来检查用户的输入以查看它是否是回文。我的代码如下,但位于:

if(isPalindrome() = true)
     System.out.println("You typed a palindrome!");

我收到错误消息“赋值的左侧必须是变量”。不是一个变量吗?我能做什么来解决它?如有任何建议,我们将不胜感激!

public class PalindromeChecker
{
public static void main(String [] args)
{
    String answer;
    while(answer.equalsIgnoreCase("y"))
    {
        System.out.println("Please enter a String of characters.  I will check to see if");
        System.out.println("what you typed is a palindrome.");
        Scanner keys = new Scanner(System.in);
        String string = keys.nextLine();
        if(isPalindrome() = true)
            System.out.println("You typed a palindrome!");
        else
            System.out.println("That is not a palindrome.");
        System.out.print("Check another string? Y/N: ");
        answer = keys.next();
    }
}

public static boolean isPalindome(String string)
{
    if(string.length() <= 0)
        System.out.println("Not enough characters to check.");
    string = string.toUpperCase();
    return isPalindrome(string,0,string.length()-1);
}

private static boolean isPalindrome(String string, int last, int first)
{
    if(last <= first)
        return true;
    if(string.charAt(first) < 'A' || (string.charAt(first) > 'Z'))
        return isPalindrome(string,first + 1, last);
    if(string.charAt(last) < 'A' || (string.charAt(last) > 'Z'))
        return isPalindrome(string,first, last - 1);
    if(string.charAt(first) != string.charAt(last))
        return false;
    return isPalindrome(string,first + 1, last - 1);
}
}

最佳答案

使用双等于==进行比较。单个等号 = 是赋值运算符。

if (isPalindrome() == true)

或者更好的是,对于 boolean 比较,根本不使用 == 。如果你只是写的话,它读起来更像英语:

if (isPalindrome())

关于java - 带递归的回文检查器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595890/

相关文章:

javascript - 如何在 typescript 中找到树中的树

java - 递归谢尔宾斯基三角 Java

java - Junit 测试用例中未知主机的 GET 请求发生 I/O 错误

java - 两次调用 Spring AOP 建议

java - 在 axis/rampart 客户端中禁用 InclusiveNamespaces

java - 用Java连接Advantage数据库

python - 通过递归仅获取数字中的奇数位

python-3.x - odoo 11/Python 3 : How to find expiry date of subscription if some weekdays are excluded

java - 如何为eclipse项目实现属性页

c++ - 如果在指令之前调用递归函数怎么办?