因此,我的程序的前提是它是一個JavaFX GUI,它將顯示「分析」的結果。遞歸方法導致Java程序中的堆棧溢出
我有6個不同的串從長度爲1至長度爲3
String[] phrases = new String[] { "ar", "ne", "um", "ll", "r", "ose" };
以及對象,其中我只使用的名稱(字符串值)的ArrayList。
到目前爲止,我已經能夠設置循環來提供數據來顯示GUI。
private void analyzePlantMenu(ArrayList<Plant> plants)
{
String[] phrases = new String[] { "ar", "ne", "um", "ll", "r", "ose" };
BorderPane sects = new BorderPane();
String current = "";
TextArea analysis = new TextArea();
for (Plant myplant : plants)
{
current = myplant.getName();
for (int q = 0; q < phrases.length; q++)
{
String trial = phrases[q];
analysis.appendText("The number of times " + phrases[q] + " appeared in the word " + current + " were "
+ compareTrials(trial, current) + "\n");
}
}
我在爲compareTrials
這裏返回正確的值麻煩的是遞歸方法我到目前爲止
private int compareTrials(String trial, String current)
{
int shift2 = 0 + trial.length();
int shift = 0;
if (shift == current.length())
{
return 0;
}
else if (current.substring((shift), (shift2)).contains(trial))
{
shift2 += 1;
shift += 1;
return 1 + compareTrials(trial, current);
}
else
{
shift2 += 1;
shift += 1;
return 0 + compareTrials(trial, current);
}
}
有人可以幫助我瞭解爲什麼我迭代單詞時出現堆棧溢出錯誤?
我最好的猜測是,有可能是因爲我的基本情況是不是基本情況或我有我else語句的方式,它會繼續無限期
編輯
方式我開始改變我的方法來檢測這些值,而不是進入堆棧溢出,而是將多個變量移動到方法的外部並將它們傳入。化妝品的變化及以下
private void analyzePlantMenu(ArrayList<Plant> plants)
{
String[] phrases = new String[] { "ca", "in", "us", "ll", "r", "ose" };
BorderPane sects = new BorderPane();
String current = "";
TextArea analysis = new TextArea();
for (Plant myplant : plants)
{
current = myplant.getName();
for (int q = 0; q < phrases.length; q++)
{
String trial = phrases[q];
**int total = 0;
int shift2 = trial.length();
int shift = 0;**
analysis.appendText((q+1) + ". The number of times " + phrases[q] + " appeared in the word " + current
+ " were " + compareTrials(trial, current, shift, shift2, total) + "\n");
}
analysis.appendText("Finished analysis of " + current.toUpperCase() + "\n");
analysis.appendText("\n");
}
編輯代碼和遞歸方法
private int compareTrials(String trial, String current, int shift, int shift2, int total)
{
if (shift2 >= current.length() + 1)
{
System.out.println(shift + " " + shift2);
return total += 0;
}
else if (current.substring((shift), (shift2)).equalsIgnoreCase((trial)))
{
System.out.println(shift + " " + shift2);
return total += 1 + compareTrials(trial, current, shift + 1, shift2 + 1, total);
}
else
{
System.out.println(shift + " " + shift2);
return total += 0 + compareTrials(trial, current, shift + 1, shift2 + 1, total);
}
}
您的停止條件是'current'長度爲0,從不發生,因爲它不會改變。我認爲你需要將'substring'(在'else if'語句中)的結果影響到'current'(或其他變量)。 – neomega
好的。 ** shift2 **和** shift 1 **變量是我從當前單詞左端開始到單詞右端的嘗試。在遞歸中是否可以像這樣遞增? – KMonkey
你可以通過將這些參數作爲'compareTrials'方法的參數:'compareTrials(String trial,String current,int shift,int shift2)'。但它似乎過於複雜。請參閱我的迴應以瞭解一般想法。 – neomega