## Posted By

DrPepper on 01/26/11

# [Java] CH6 Fibonacci Number Calculator

/ Published in: Java

`/**    the fibonacci sequence is defined by the following rule. the first two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. For example, the third value is 1 + 1 = 2, the fourth value is 1+2=3, and the fifth is 2+3 =5. If fn denotes the n the value in the fibonacci sequence, then    f1 = 1    f2 = 1    fn = fn-1 + f2-2 if n > 2    write a programing that prompts the user for n and prints the first n values in the fibonacciGenerator with a methof nextNumber.Hint: there is no need to store all values for fn you only need the last two values to compute the next one in the series:    fold1 = 1;    fold2 = 1;    fnew = fold1 + fold2    after that, discard fold2,which is no longer needed, and set fold2 to fold1 and fold1 to fnew.    your generator class will be tested with this runner program:     public class FibonacciRunner    {        public static void main(String[] srgs)        {            Scanner in = new Scanner(System.in);            System.out.println("Enter n : ");            int n = in.nextInt();            fibonacciGenerator fg = fibonacciGenerator();             for(int i = 1; i<= n; i++)                System.out.println(fg.nextNumber());        }    }*/import java.util.Scanner;                 public class Fib{     public static int fold1;    public static int fold2;    public static int fnew;     public Fib()    {        fold1 = 0;        fold2 = 1;    }     public static int nextNumber()    {        fnew = fold1 + fold2;        return fnew;    }         public static void deleteNumber()    {        fold1 = fold2;        fold2 = fnew;    }     public static void main(String[] srgs)    {        Fib fb = new Fib();        Scanner in = new Scanner(System.in);        System.out.println("Enter n : ");        int n = in.nextInt();        System.out.println("*** Fibonacci Numbers ***");        for(int i = 1; i<= n; i++)        {               int nextNum = nextNumber();            System.out.println(nextNum);            deleteNumber();        }     }}`