首先這不是功課。只是我在練習。 我試圖遞歸確定「hi」出現在給定字符串中的次數,但在每種情況下,它跳到最後一個else語句以及字符串爲空的事情。有任何想法嗎?Java遞歸計數
基本上, 如果 增量次數由1(串「喜」開頭),並與第二索引後的字符串遞歸跳過了「喜」,它只是計算
否則,如果(String不以「hi」開始並且字符串不爲空) 在第一個索引後遞增字符串,以查看下一次是否以「hi」開頭。
else if(string is empty) Print(「End of text reached」) return count;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
在字符串處理[wiki](http://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Recursive_procedures)中,有更好的例子可以從遞歸練習開始。 – PeterMmm
我對此有疑問 - 任何呼叫者都可以修改結果,因爲'counter'是外部呼叫的一部分。至少,這應該做'私人',用一個'public'包裝,不包含'計數器'(並且不遞歸)。另一種方法是在遞歸返回期間進行加法。此外,您正在使用'startsWith'檢查,然後將光標移動1 - 'indexOf'有什麼問題(我認爲可用的更好的優化)。 –