Question

I am trying to write a Java program that produces the "nth" Fibonacci number. What am I doing wrong?!

 public class project7 {

    public static void main(String[] args) {
        ConsoleReader console = new ConsoleReader(System.in);

        int fold1 = 1;
        int fold2 = 1;


        System.out.println("Enter the number of times you would like to compute:");
        int n = console.readInt();

        for(int i = 0; i <= n; i++ ){

            fold1++;
            fold2++;
        }

        int fnew = fold1 + fold2;
        System.out.println(fnew);

    }
}
Was it helpful?

Solution

What exactly are u expecting other than just a number ?? So first u initialize a console reader to get user input. Then you initialize 2 Integers to the Value 1 ... fold1 and fold2 ... Then you get an input value for int n ... All of that is wonderful. Then you make n+1 loops incrementing fold1 and fold2 ... ok .. Then u add them in fnew and print the result ... that's what this code does. Say u get an input of 5 ... fold1 is gonna get incremented 6 times starting with 1 so in the six loops (because of <=) it's values will be 2,3,4,5,6,7 ... same for fold2 ... printing fnew to be14

update:

Try this int fold1 =0; int fold2 =1; int n = console.readInt ...

for(int i=0; i<n;i++)
{
Fnew = fold1 + fold2;
fold1 = fold2;
fold2 = Fnew;

} System.out.println(Fnew);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top