Java Reference
In-Depth Information
public class PowerGenerator
{
/**
Constructs a power generator.
@param aFactor
the number that will be multiplied
by itself
*/
public PowerGenerator(int aFactor) { . . . }
/**
Computes the next power.
*/
public double nextPower() { . . . }
. . .
}
279
280
Then supply a test class
PowerGeneratorRunner
that calls
System.out.println(myGenerator.nextPower())
twelve
times.
Exercise P6.4. 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 f
n
denotes
the first nth value in the Fibonacci sequence, then
= 1
f
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 nth value in the
Fibonacci sequence. Use a class
FibonacciGenerator
with a method
nextNumber
.
Hint: There is no need to store all values for f
n
. You only need the last two
values to compute the next one in the series:
fold1 = 1;
fold2 = 1;