我用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
您忘記了'if'返回':'return isPalidrome(...)'。 –
你爲什麼使用遞歸? – Bathsheba