简体   繁体   中英

How to generate Fibonacci series in ArrayList

Currently I am working on a task, where I should prompt the user to input a number from the console (eg 1) and then:

  • First two elements of ArrayList are the input number(1);
  • Every next element at the ArrayList is equal to sum of previous two;
  • Print the ArrayList.

Here is my trainee code:) :

public class ex3 {
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number :");
    int number = sc.nextInt();

    List<Integer>numbersList = new ArrayList<>();
    numbersList.add(number);
    numbersList.add(number);

    int k = 0,a = number,b = number;
    for(k=0;k<=10;k++) {
        k = a + b;
        System.out.println(k + " ");
        a=b;
        b=k;
    }
  }
}

I see that obviously I have not put the fibonacci series into the ArrayList.

Please find the solution below:

import java.util.*;

public class ex3{
        
    public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a number :");
      int n = sc.nextInt();

      List<Integer> numbersList = new ArrayList<>();
      int first = 0, second = 1, fib;
      numbersList.add(first);
      numbersList.add(second);
      
      for(int i = 2; i < n; i++) {
          fib = second + first;
          first = second;
          second = fib;
          numbersList.add(fib);
      }
      System.out.println(numbersList);
  }
}
for(int i=2;i<range;i++){
numberslist.add(numberslist.get(i-1)+numberslist.get(i-2))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM