2017-02-03 93 views
-4

我不明白爲什麼我得到「返回語句丟失」。Java初學者遞歸與布爾值

下面是該代碼的圖像:
enter image description here

+0

所有路徑都不返回一個值.... –

+0

您要在elseif條件中返回某些內容。 –

+2

請將代碼作爲文本附加,而不是圖片。這對於其他人來說更容易閱讀 –

回答

1

在你的第二和第三個條件,如果沒有回報。而不是其他人,只需返回false。

,所以它讀取:

public class isTrans { 
     public static boolean isTrans(String s,String t) { 
      if (t.length()==1 && (s.charAt(s.length()-1))==t.charAt(0)){ 
       return true; 
      } else if (s.charAt(0)==t.charAt(0)){ 
       return isTrans(s,t.substring(1)); 
      } else if (s.charAt(1)==t.charAt(1)){ 
       return isTrans(s,t.substring(1), t); 
      } 
      return false; 
     } 
    } 
+0

如果我刪除其他只有留下返回假我總是得到返回假 – OLY

+1

謝謝youuuuuuu sooooo muchhhhhhhhh – OLY

+0

非常歡迎! – SPlatten

0

在這種情況下,你必須在所有的條件下返回或在方法的最後返回。

0
if(/*...*/) { 
    return true; 
} 
else if(/*...*/) { 
    return isTrans(/*...*/); // return whatever isTrans returns 
} 
else if(/*...*/) { 
    return isTrans(/*...*/); // here too 
} 
else { 
    return false; 
} 
+1

儘管您可能已經解決了此用戶的問題,但僅有代碼的答案對於未來出現此問題的用戶並不是很有幫助。請編輯您的答案,以解釋爲什麼您的代碼可以解決原始問題。 –

0

您必須在else if中返回函數執行的結果,以便遞歸正常工作。像這樣:

return isTrans(s, t.substring(1))