2012-11-28 78 views
0

我正在做一个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); 
} 
} 

回答

3

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

if (isPalindrome() == true) 

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

if (isPalindrome()) 
+1

有没有isPalindrome(),虽然。 –

+0

@usernametbd是的,在这之后OP还需要处理各种其他问题。不仅仅是编译时错误。 –

+0

尝试了这一点,我得到“PalindromeChecker类型中的方法isPalindrome(String,int,int)不适用于参数(字符串)” – Derek

1

你的方法调用应该是:isPalindrome期待字符串参数:

if(isPalindome(string)) 

而且你也不需要做平等检查,因为返回类型是无论如何布尔值。

+0

尝试了这一点,我得到“PalindromeChecker类型中的方法isPalindrome(String,int,int)不适用于参数(字符串)” – Derek

+0

它应该是isPalindome,而不是isPalindrome,请注意r丢失。看我的编辑。 – kosa

0

使用

if(isPalindome(string)==true) 

相反。

两个变化:

1)你需要传递给stringisPalindome

2)为了比较,您需要使用两个等号,而不是一个。

而且,我相信你的意思是不是写“isPalindrome”,而不是“isPalindome”

+0

我试过了,我得到了“PalindromeChecker类型中的方法isPalindrome(String,int,int)不适用于参数(字符串)” – Derek

+0

再次,您将'isPalindome'而不是'isPalindrome'作为你的方法名称 - 解决这个问题应该消失。 –

+0

* facepalm *哇我觉得很聪明。哈哈感谢的人,我很感激:P – Derek