2016-04-22 49 views
1

我用Java编写了回文功能,但是它的打印结果不正确。这个回文功能有什么问题

public static boolean isPalindrome(String test) { 
     if(test.length() == 1 || test.equals("")) { 
      System.out.println("Length is one"); 
      return true; 

     } 

     if (test.charAt(0) == test.charAt(test.length() - 1)) { 
      System.out.println("Length is one 111 a"); 
      isPalindrome(test.substring(1,test.length() -1)) ;  
     } 
     System.out.println("Length is one 111"); 
     return false; 
    } 

    public static void main(String args[]) { 
     if(isPalindrome("rotor")) 
      System.out.println(" Rotor is a palindrome"); 
     else 
      System.out.println(" Rotor is not a palindrome"); 
     //System.out.println(isPalindrome("rotor")); 
     //System.out.println(isPalindrome("motor")); 
     //System.out.println(isPalindrome("a")); 

    } 

输出:

Length is one 111 a 
Length is one 111 a 
Length is one 
Length is one 111 
Length is one 111 
Rotor is not a palindrome 
+2

您忘记了'if'返回':'return isPalidrome(...)'。 –

+0

你为什么使用递归? – Bathsheba

回答

2

你缺少ifreturn声明。没有它,什么,但一个或零字符的字符串将最终回归false

public static boolean isPalindrome(String test) { 
    if(test.length() <= 1) { // A more elegant check 
     return true; 
    } 

    if (test.charAt(0) == test.charAt(test.length() - 1)) { 
     // "return" was missing here 
     return isPalindrome(test.substring(1, test.length() -1)) ;  
    } 
    return false; 
} 
+1

此外,你的字符比较区分大小写,这仍然会导致'Rotor'失败。 – Zircon

+0

@锆石,而OP的输出是关于'转子',他的'主'实际上检查串'转子'。虽然我同意,但如果我们要检查“不区分大小写的回文”,则应该使用Character#equalsIgnoreCase而不是原始'char'的简单'=='。或者,也可以是小写(或大写)两个字符。 – Mureinik

1

你的问题基本上是从一个贫穷的解决方案技术干。递归是解决这个问题的次优方式 - 考虑JVM必须创建的所有堆栈框架!如果你能沟的办法,并愿意牺牲简洁的表现,然后用

return test.equalsNoCase(new StringBuilder(test).reverse().toString());

这显然是相当容易维护(虽然这将创建两个额外的对象执行两倍许多字符比较是必要的)。如果您认为案例对于回文是重要的,请使用equals

1

必须在此处添加回报:

if (test.charAt(0) == test.charAt(test.length() - 1)) { 
      System.out.println("Length is one 111 a"); 
      return isPalindrome(test.substring(1,test.length() -1)) ; 
     } 
     System.out.println("Length is one 111"); 
     return false; 

如果你不这样做,它只会继续测试完最后一次通话(你的情况为串“T”)后执行,它会结束返回false。