Question

I have the task of writing a program using the fibonacci sequence and putting them into arrays. It works by getting user input ( how many numbers in the sequence the user wants to print out) and then it implements that into an array and prints out the sequence with the number of 'numbers' the user inputed. As I missed out on 2 weeks of class I looked online on how to write this program and found a video which the following code was written. So I do not take credit for the following code, I'm merely using it as an example.

Anyway here's the code:

public class Fibonacci
{
    public static void main(String[] args)
    {
        int numToPrint;
        //how many numbers to print out

        Scanner scan = new Scanner(System.in);
        System.out.println("Hvað viltu prenta út margar tölur úr Fibonacci röðinni?");
        numToPrint = scan.nextInt();
        scan.close();

        //prints out the first 2 numbers
        int nuverandiT = 1;
        int lokaT = 0;
        System.out.println(lokaT);
        System.out.println(nuverandiT);

        //prints out the rest of the sequence
        int lokaLokaT;
        for(int i = 2; i < numToPrint; i++)
        {
            lokaLokaT = lokaT;
            lokaT = nuverandiT;
            nuverandiT = lokaLokaT + lokaT;
            System.out.println(nuverandiT);
        }
    }
}

Now this prints out the fibonacci sequence with input from the user, but I'm not quite sure how to make it print out into an array. Do any of you guys know how to do this?

Était-ce utile?

La solution

You have to create an array, for example:

int[] simpleArray;
simpleArray = new int[numToPrint];

At the place of

System.out.println(lokaT);
System.out.println(nuverandiT);

Put:

simpleArray[0] = lokaT;
simpleArray[1] = nuverandiT;

And inside your loop, you put instead this:

System.out.println(nuverandiT);

This: simpleArray[i] = nuverandiT;

Autres conseils

I'm guessing when you say 'print out into an array' you really mean you just want to store the values in an array. In that case,

Before your for loop:

int[] array = new int[numToPrint];

And inside your for loop:

array[i-2] = nuverandiT;

If you wanted to print the numbers once they've been stored in an array, you would probably want to loop through it and print in the same fashion, accessing the elements by index. For more information, the java documentation is very good. I recommend reading up on arrays and counted loops.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top