This is a continuation from: Recursive Fibonacci memoization.
I keep getting
an java.lang.ArrayIndexOutOfBoundsException
error when trying to run the code. I m getting the error on lines 63 and 40 which are
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