I'm a absolutly beginner in java and i want to write a code with the acm.libary, which is about the fibonacci sequence.
The result is very nice for me, but i want only print the last number of the sequence. I don't know how.
If the user type n = 5, the result need to be 8.
If the user type n = 8, the result need to be 21.
In my program it is the last number, but the program also prints all the previous numbers.
I hope you can understand me :D
Thank you in advance!
int a = 1;
int b = 0;
public void run() {
int n = readInt ("n: ");
for(int i = 1; i <= n; i++) {
println (fibonacci (n));
}
}
private int fibonacci(int n) {
int c = (a) + (b);
a = b;
b = c;
return c;
}
Try this code.
import java.util.Scanner; public class Test { int a = 1; int b = 0; public int run() { @SuppressWarnings("resource") Scanner s = new Scanner(System.in); int n = s.nextInt(); int value =0; for(int i = 1; i <= n; i++) { value = fibonacci (n); } return value; } private int fibonacci(int n) { int c = (a) + (b); a = b; b = c; return c; } public static void main (String arg[]) { Test t = new Test(); System.out.println(t.run()); } }