这是以下内容的延续: Recursive Fibonacci memoization
我一直在努力
尝试运行代码时出现java.lang.ArrayIndexOutOfBoundsException
错误。我在第63和第40行得到错误
63: int fib = dictionary[num]; // dictionary is a class level array.
40: answer = fibonacci(num); // Answer is an int calling the fibonacci function and passing "num" to it.
以下是完整代码:
import javax.swing.JOptionPane;
public class question2
{
//class variable
static int count = 0;
static int [] dictionary;
//main method
public static void main(String[] args)
{
//user input
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter num:")), answer;
//Catches negative numbers, exits
if (num < 0)
{
JOptionPane.showMessageDialog(null,"ERROR: fibonacci sequence not defined for negative numbers.");
System.exit(1);
}
//info dialog
JOptionPane.showMessageDialog(null,"About to calculate fibonacci("+num+")");
//giving the array "num" elements
dictionary = new int [num];
//fill array with 0
for (int i=0; i<dictionary.length;i++)
dictionary[i]=0;
//adds value of 1 for fib(1)
if (dictionary.length>=2)
dictionary[1]= 1;
//method call
answer = fibonacci(num);
//output
JOptionPane.showMessageDialog(null,"Fibonacci("+num+") is "+answer+" (took "+count+" calls)");
}
static int fibonacci(int num)
{
count++;
// Base cases: f(0) is 0, f(1) is 1
if (num==0)
return 0;
if (num==1)
return 1;
// Other cases: f(num) = f(num-1) + f(num-2)/
else
{
//check array for value
int fib = dictionary[num];
//add new value to array
if (fib==0)
{
fib = fibonacci(num-1) + fibonacci(num-2);
dictionary[num] = fib;
}
return fib;
}
}
} //class terminator
答案 0 :(得分:6)
数组的大小为num
(int fib = dictionary[num];
),因此您可以访问的最大索引为num-1
。您尝试访问超出范围的索引num
(dictionary[num] = fib;
)。