# Fibonacci generator and gives the number back as output

• June 19th, 2009, 07:59 PM
aurora
Fibonacci generator and gives the number back as output
I have a program that i need to complete. I wrote the first one (FibonacciGenerator) with stated variables - everything worked fine
I now want to split it up so that the user can give a number and the program gives the correct number back. (ie, fib(5)=5 AND NOT fib(5)=2)
Please help as I know what i need to do but the how escapes me.

constructor portion
Code :

``` /* Class used to generate a Fibonacci number with a given input */ public class FibonacciGenerator { /** Construct a FibonacciGenerator object to generate a Fibonacci number */ public FibonacciGenerator() { initialize(); }   /** Initializes the FibonacciGenerator object. Allows the object to be reset and reused. */   public void initialize() { fold1 = 1; fold2 = 1; fnew = 1; count = 0; } /** Method used to calculate a fibonacci number @return fnew the fibonacci number */ public int nextNumber() { if(count < 2) { count++; return 1; } else { fnew = fold1 + fold2;   fold2 = fold1; fold1 = fnew;   return fnew; } }   private int fold1; private int fold2; private int count; private int fnew; }```

Test Program (I know i need to return the input to the constructor file but how??)
Code :

``` import javax.swing.JOptionPane;   /** Test driver class for FibonacciGenerator class */ public class FibonacciGeneratorTester { public static void main(String[] args) { String input = JOptionPane.showInputDialog( "Enter a Number or hit ''Cancel'' to exit:"); int n = Integer.parseInt(input);   FibonacciGenerator fg = new FibonacciGenerator();   int next = n;   if (n < 2) next = 1; else { for (int i = 3; i <= n; i++) { next = fg.nextNumber(); } }   System.out.println("fib(" + n + ") = " + next);   System.exit(0); } }```

Any help is appreciated
• June 20th, 2009, 12:58 AM
Freaky Chris
Re: help with FibonaccciGenerator
Welcome to Java Programming Forums, Aurora.

Have a read of this, a previous topic about the fibonacci sequence see if it helps you out. If it doesn't then get back to us and I'll have a proper look over your code.

http://www.javaprogrammingforums.com...-sequance.html

Regards,
Chris