I'm having some trouble with my program for the final project.
My assignment is to take a user input of how many digits of the fibonacci sequence they wish to display, and then....display them.
However when I first ran the code, it would throw an ArrayOutofBounds exception.
So say the user input 5, the system would print out the first three correctly but then give me the exception. Which I understand to be that it's calling reserved array spots that don't exist. I fixed the code by adding 2 to the user input which defines the array size, but I feel like there has to be a better way.
import javax.swing.*; public class Fibonacci { private static String strFibN; protected static int intFibN; //public static void UserInput() public static void main(String[] args) { strFibN = JOptionPane.showInputDialog(null, "Please Input the Amount of Numbers you Wish to Display of the Fibonacci Sequence"); intFibN = Integer.parseInt(strFibN); int[] Fib = new int[intFibN + 2]; Fib[0] = 1; Fib[1] = 1; for(int inc=0; (inc)<intFibN; inc++) { Fib[(inc + 2 )] = Fib[inc] + Fib[(inc + 1)] ; System.out.println(Fib[inc]); } } }
The reason for the formula being + 2 is because I've already got the first two digits so the next array slot to be filled should be Fib[2] but I'm sure you all gathered that.
Also, I'd like the output to be in JOptionPane format, but I can't seem to get it to work without having to click ok, for every single array slot, which is just a pain. Any thoughts?