The Fibonacci sequence is a series of values in which each successive value is the sum of the previous two values. The first two values in the sequence are 1 and 1, or 0 and 1, depending on which system one chooses. We’ll use the second system for this problem and use a computer science-based numbering system, so
Write a FibonacciGenerator
with a method nextNumber()
that returns each time it is called the next number in the Fibonacci sequence.
Sample use in a program:
FibonacciGenerator fg = new FibonacciGenerator();
System.out.println(fg.nextNumber()); --> 0
System.out.println(fg.nextNumber()); --> 1
System.out.println(fg.nextNumber()); --> 1
One of the challenges in this program is keeping track of the values we’re working with. Consider this strategy: Identify the 0th and 1st fibonacci values and store them in two variables. Based on these, calculate the next value and store that in a third variable. Every time the nextNumber
method is called, take note of the value that you’re going to return (the first time it will be the 0th value), replace the values of each variable in anticipation of the next time the method is called, and finally return the actual next value.
Once your FibonacciGenerator
class is working write a program FibonacciRunner
that asks the user to enter the highest Fibonacci number they want to see. The Runner should then instantiate a FibonacciGenerator and use a for
-loop to call nextNumber()
repeatedly, and print out all the Fibonacci numbers up to and including that index.