【发布时间】:2021-03-04 17:30:07
【问题描述】:
如果有人向我解释这个问题的解决方案,我也将不胜感激,因为我认为我的逻辑不正确。
public class FibanacciSequence {
public static void main(String[] args)
{
fibSeq(5,5);
}
public static int[] fibSeq(int startNum, int iterations)
{
int[] arr = new int[iterations];
int nextNum = 0;
arr[0] = startNum;
if(iterations == 0)
{
return arr;
}
else
{
arr[nextNum] = startNum+startNum;
arr[nextNum+1] = nextNum + startNum;
arr=fibSeq(nextNum,iterations-1);
}
return arr;
}
}
【问题讨论】:
-
想象一下当您调用
fibSeq(0, 1)时会发生什么(在某些时候会发生,无论您的初始参数如何)您创建了一个大小为1的数组,但尝试访问索引0和@ 987654325@。大小为 1 的数组没有索引1。还有图像,如果您到达iterations == 0的位置会发生什么。您创建一个大小为0的数组并尝试在索引0处设置值,这显然不能存在于大小为0 的数组中 -
对于问题问题的一般帮助,您应该首先解释一下,您正在尝试做什么......
-
这是学习使用调试器单步调试代码的最佳时机。你可以观察变量的值,看看哪里有逻辑错误,让你跑到数组的末尾。
-
此外,您正在向某个数组添加值,然后用您的递归调用的结果替换整个数组。因此,抛开所有越界异常,您的结果将始终是一个空数组
标签: recursion indexoutofboundsexception