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 nth value in the Fibonacci sequence, then

f 1 = 1
f 2 = 1
f n = f n-1 + f n-2 if n > 2

Write a program that prompts the user for n and prints the first n values in the Fibonacci sequence. Use a class FibonacciGenerator with a method 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[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter n:");
      int n = in.nextInt();

      FibonacciGenerator fg = new FibonacciGenerator();

      for (int i = 1; i <= n; i++)
         System.out.println(fg.nextNumber());
   }
}

Complete the following file:

FibonacciGenerator.java

/** 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() { . . . } /** Method used to calculate a fibonacci number. @return fNew the fibonacci number */ public int nextNumber() { . . . } }

Use the following file:

FibonacciRunner.java

import java.util.Scanner;

public class FibonacciRunner
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      
      System.out.println("Enter n:");
      int n = in.nextInt();

      FibonacciGenerator fg = new FibonacciGenerator();

      for (int i = 1; i <= n; i++)
         System.out.println(fg.nextNumber());
   }
}