public class FibonacciGenerator
{
//instance variables
private int recent ; //one values ago
private int previous ; //two values ago
private int n ; // the number of values returned so far
/**
Constructs the generator by setting the instance variables to 1
*/
public FibonacciGenerator()
{
recent = 1 ;
previous = 1 ;
n = 0 ;
}
/**
Produces the next Fibonacci number
@return the next in the Fibonacci sequence
*/
public int next()
{
n ++ ;
if (n == 1) return 1 ;
if (n == 2) return 1 ;
int result = recent + previous ;
//----------------Start below here. To do: approximate lines of code = 3
// 1. Update previous and recent, and 2. return result.
previous++;
recent++;
return result;
//----------------------End here. Please do not remove this comment. Reminder: no changes outside the todo regions.
}
}
import java.util.* ;
public class FibonacciGeneratorTester
{
public static void main(String[] args)
{
System.out.println("The 1st Fibonacci number is: "
+ getFibonacci(1)) ;
System.out.println("The 10th Fibonacci number is: "
+ getFibonacci(10)) ;
}
/**
A static method to return the n'th Fibonacci number
@param n the index of the Fibonacci number
@return the n'th Fibonacci number
*/
public static int getFibonacci(int n)
{
FibonacciGenerator generator = new FibonacciGenerator() ;
int result = 0 ;
//----------------Start below here. To do: approximate lines of code = 4
// 1. Write a for-loop that calls the generator n times 2 . return the last result of the call.
for (int i = 1; i <= n; i++){
generator.next();
return result;
}
}
}
缺少返回語句第二個最後一個大括號突出顯示。我的for循環是否正確?............................................ .................................................. .................................................. .......缺少return return語句Fibonnacci Java
你'previous'和'recent'將永遠是相同的,因爲它們都開始於一個都是由一個總是在同一時間遞增。這已經把你想要的結果搞砸了。 –