我正在制作一个java程序,用于检查用户的输入以查看它是否是回文。 我的代码在下面,但在:
if(isPalindrome() = true)
System.out.println("You typed a palindrome!");
部分 I 收到错误,说"赋值的左侧必须是变量"。 它不是一个变量吗?我能做些什么来修复它? 任何建议不胜感激!
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)
或者更好的是,对于布尔比较,根本不使用==
。如果你只是写,它读起来更像英语:
if (isPalindrome())
您的方法调用应该是: isPalindrome 期望字符串参数:
if(isPalindome(string ))
而且你不需要做相等性检查,因为返回类型无论如何都是布尔值。
使用
if(isPalindome(string)==true)
相反。
两个变化:
1)您需要将string
传递给isPalindome
。
您需要使用两个等号,而不仅仅是一个等号。
另外,我相信你可能想写"isPalindrome"而不是"isPalindome"