0

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.

Here is the full code:

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
Community
  • 1
  • 1
Eogcloud
  • 1,335
  • 4
  • 19
  • 44
  • 2
    If you get totally stuck at this sort of thing, going through it with a debugger's the way to go. – G_H Oct 24 '11 at 14:28

1 Answers1

6

The array is of size num (int fib = dictionary[num];) so the max index you can access is num-1. You try to access index num (dictionary[num] = fib;) which is out of bounds.

MByD
  • 135,866
  • 28
  • 264
  • 277