我想做一個遞歸類,它需要一個string
作爲參數,並從字符串列表返回一個以參數字符串開頭的行。如果找不到匹配,它應該返回「」。我似乎幾乎在那裏,但由於某種原因,一旦找到字符串並輸入if語句,它會返回字符串,但會跳轉到代碼中的其他語句。換句話說,由於某種原因,它不會返回它。任何幫助真的會有所幫助。Java-在遞歸類中返回字符串的問題
public String getLineStartingWith(String _string){
System.out.println("GETLINESTRING: " + _string);
//place parameter string into local string
String string = _string;
//return the line from the stringlist if it starts with the
//parameter string
if(currentString.startsWith(_string)){
System.out.println("CURRENT STRING: " + currentString);
return currentString;
}
restOfList.getLineStartingWith(_string);
return "";
//return restOfList.getLineStartingWith(_string);
}
編輯
我做了一些改變,以我的代碼。但由於某種原因,在它返回當前字符串後,它每次都返回restOfList.getLineStartingWith(string)。我認爲它不檢測它是否爲空
public String getLineStartingWith(String string){
System.out.println("GETLINESTRING: " + string);
//return the line from the stringlist if it starts with the
//parameter string
if(currentString.startsWith(string)){
System.out.println("CURRENT STRING: " + currentString);
return currentString;
}
if(restOfList.isEmpty){
return "";
}
return restOfList.getLineStartingWith(string);
}
因此,我剛剛離開那裏沒有理由的第一部分。我的錯。當你的意思是基本情況下,這是什麼意思? – Splitusa
@SergioRa - 在遞歸中,基本情況就是你知道答案的情況。例如,在你的程序中,'if(currentString.startsWith(_string)){'部分是一個基本情況,因爲你在該點遞歸調用函數。當你有答案時,你有一個基本的例子,當你沒有答案時,你只需要一個答案。 –
好吧,我開始明白,我想。所以像這樣:if(restOfList.isEmpty){return「」; }空白是一個布爾值。 – Splitusa