File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Fibonacci Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Fibonacci" Watch "Fibonacci" New topic


RH Gomez

Joined: Oct 15, 2005
Posts: 2
Hi, I'm having some trouble with a program I'm trying to write.. in theory I know what to do but my code seems to have more than one error. The program must ask the user for a number (n) and return the first n numbers of the fibonacci sequence. Any help will be apreciated.
This is the code

import acm.program.*;

public class ProgramaFibonacci extends ConsoleProgram {

public static void main(String[] args) {
new ProgramaFibonacci().start();

public void run() {

int n = this.readInt("Dame un n�mero entero: ");

int n1 = 1;
int n2 = 1;
int i = 2;

if ((n == 0) || (n == 1)) {
n1 = 1;
} else {
for (i = 2; i <= n; i++) {
n1 = n2 + i;
i = n2;
n2 = n1;

return n;

marc weber

Joined: Aug 31, 2004
Posts: 11343

First, please use CODE tags to keep your formatting intact. Here is your code (as you entered it) with tags...

Now, to see what's happening, take a look at the for loop, and consider what happens on the first iteration (when n1 and n2 both start as 1, and i is 2)...
n1 = n2 + i; //n1 = 1 + 2 = 3
i = n2; //i = 1
n2 = n1; //n2 = 3

Hmmm... Is that what you want? Both n1 and n2 to end up equal? Look at the next iteration (after i has been incremented to 2)...
n1 = n2 + i; //n1 = 3 + 2 = 5
i = n2; //i = 3
n2 = n1; //n2 = 5

And then (after i has been incremented to 4)...
n1 = n2 + i; //n1 = 5 + 4 = 9
i = n2; // i = 5
n2 = n1; //n2 = 9

Basically, you're using the variable i as a counter, to count from 2 to n. But within your for loop, you're assigning i a different number. I think you would do better using n1 and n2 to store your sequence values, and leave i alone to count.

Also, when you're done, you probably don't want to return n.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
marc weber

Joined: Aug 31, 2004
Posts: 11343

Another tip: You should give your variables more descriptive names. This makes it easier for others to read your code, and it also might help you to keep things straight.

For example, instead of n, i, n1, and n2, you might use limit, iteration, currentNumber, and previousNumber.
I agree. Here's the link:
subject: Fibonacci
It's not a secret anymore!