2017-04-10 65 views
-1

我想檢查一個單詞是否是迴文,我正在使用遞歸,我不知道我在做什麼錯,但是當我到達基本情況時,該方法一直調用最終所有字返回錯誤。任何人都可以幫我找到錯誤嗎?謝謝:/返回語句不停止代碼java

public static void main(String[] args) 
{ 
    System.out.print("Enter a word: "); 
    Scanner sc = new Scanner(System.in); 
    String isPalindrome = sc.next(); 
    String regex = "[.!? ]"; 
    isPalindrome.split(regex); 
    if(testPalindrome(isPalindrome)==true) 
    { 
     System.out.print(isPalindrome+" is a palindrome."); 
    } 
    else 
    { 
     System.out.print(isPalindrome+" is not a palindrome."); 
    } 
} 
public static boolean testPalindrome(String word) 
{ 
    if(word.charAt(0)==word.charAt(word.length()-1)) 
    { 
     if(word.length()==1) 
     { 
      return true; 
     } 
      word = word.substring(1, (word.length()-1)); 
      testPalindrome(word); 
    } 
    return false; 
} 

回答

5

您需要返回遞歸調用的結果。現在,您可以遞歸調用函數yes,但最終,因爲在進行遞歸調用時不會從函數返回,所以執行流將離開該外部語句並移至return false;,即使您遞歸併遞歸某處下線返回true

public static boolean testPalindrome(String word) 
{ 
    if(word.charAt(0)==word.charAt(word.length()-1)) 
    { 
     if(word.length()==1) 
     { 
      return true; 
     } 
     word = word.substring(1, (word.length()-1)); 
     return testPalindrome(word); 
    } 
    return false; 
} 

編輯:superhawk610也是正確的關於您的退出條件。它只對字符串中的奇數個字符有效。您應該使用類似if (word.length() <= 1)的東西來代替奇數和偶數情況。這意味着最終的代碼如下:

public static boolean testPalindrome(String word) 
{ 
    if(word.charAt(0)==word.charAt(word.length()-1)) 
    { 
     if(word.length()<=1) 
     { 
      return true; 
     } 
     word = word.substring(1, (word.length()-1)); 
     return testPalindrome(word); 
    } 
    return false; 
} 
+0

:| |我怎麼錯過了? :/非常感謝:D – noobProgrammer

+0

現在假設答案更準確。 –

0

假設你並不需要檢查在true如果作爲該方法返回一個boolean

System.out.print("Enter a word: "); 
     Scanner sc = new Scanner(System.in); 
     String isPalindrome = sc.next(); 
     String regex = "[.!? ]"; 
     isPalindrome.split(regex); 
     if(testPalindrome(isPalindrome)) 
     { 
      System.out.print(isPalindrome+" is a palindrome."); 
     } 
     else 
     { 
      System.out.print(isPalindrome+" is not a palindrome."); 
     } 

testPalindrome()方法應該是這樣的遞歸工作。

public static boolean testPalindrome(String word) 
{ 
    if(word.charAt(0)==word.charAt(word.length()-1)) 
    { 
     if(word.length()==1) 
     { 
      return true; 
     } 
      word = word.substring(1, (word.length()-1)); 
      return testPalindrome(word); 
    } 
    return false; 
} 
+0

非常感謝。 :D – noobProgrammer

+0

@noobProgrammer歡迎。 –

1

這看起來像它可以處理奇數長度的單詞,但不能處理長度均勻的單詞。更改測試的語句從

if(word.length() == 1) 

if(word.length() < 2) 

這將結束遞歸,如果你已經下調到1個字符(奇數長字的中間)或0(的「中間」一個均勻長度的詞)。