所以我的程序的前提是它是一个JavaFX GUI,它将显示“分析”的结果。
我有 6 个不同的字符串,长度从 1 到 3
String[] phrases = new String[] { "ar", "ne", "um", "ll", "r", "ose" };
以及一个对象数组列表,我只使用其名称(字符串值)。
到目前为止,我已经能够设置循环来输入数据以显示 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 语句会无限期地继续下去
编辑
我改变方法来检测这些值而不进入堆栈溢出的方法涉及将多个变量移到 compareTrials 方法之外并将它们传递进去。下面进行了外观更改和编辑的代码
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);
}
}
最佳答案
你的两个递归调用,
return 1 + compareTrials(trial, current);
和
return 0 + compareTrials(trial, current);
参数与传入参数完全相同。 试用
和当前
永远不会改变。
因此,您不能期望它收敛,因此它只是使用相同的参数无限次调用 compareTrials()
。
关于java - Java程序中递归方法导致堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34137061/