首页 > 解决方案 > 尝试将递归用于斐波那契数列(JAVA)时出现越界异常

问题描述

如果有人向我解释这个问题的解决方案,我也将不胜感激,因为我认为我的逻辑不正确。

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;
    }
}

标签: recursionindexoutofboundsexception

解决方案


当迭代 <= 0 时,您的代码将失败

arr[0] = startNum;

当 0 < 迭代次数 <= nextNum + 1 时,您的代码将失败

arr[nextNum] = startNum + startNum;
arr[nextNum + 1] = nextNum + startNum;

在编码之前,您可能应该在纸上更详细地制定您的计划。


推荐阅读