It seemed to solve a simple task, even then google the correct code ... But the console displays an array of a given value, which is filled with units. Tell me, what is the error?

public class Test { public static void main(String[] args) { prMass(fibMass(20)); } public static int[] fibMass(int x) { int m[]=new int[x]; for(int i=0;i<x;i++) { if(m[i]<2) m[i]=1; else m[i]=m[i-1]+m[i-2]; } return m; } public static void prMass(int[] x) { int z=x.length; for(int i=0;i<z;i++) { System.out.print(x[i]+" "); } System.out.println(); } } 

    4 answers 4

     for(int i=0;i<x;i++) { if(m[i]<2) m[i]=1; else m[i]=m[i-1]+m[i-2]; } 

    You for each element of the array, if its value is less than two, set the value to 1 . And go to the next item.

    Since the array was initially initialized with zeros, it is quite expected that you get an array of ones.

    • one
      It would be worth adding that you need to change the check of the element to check the index :-) - Grundy
    • Thank you, I do not even understand how it could have been overlooked .. - Artyom

    Here is another solution:

      public class Fibonacci { public static int result=0; public static int count=0; public static int a=1, b=1; public static int GenerateFibonacci(int number) { while (count<=number){ System.out.print(a+" "); b=b+a; a=ba; count++; } return result; } public static void main(String[] args) { GenerateFibonacci(5); } } 
       for(int i=0;i<x;i++) { if(i<2) m[i]=1; else m[i]=m[i-1]+m[i-2]; } 
      • @ Mihanik71, oddly enough, but the published message contains a solution to the issue - Grundy
      • @ user217504 it would be nice if you indicated exactly what the problem is - Mihanik71

      Option using stream:

        int count = 100; Stream .generate(new Supplier<BigDecimal>() { BigDecimal prevSecondNumber = BigDecimal.ZERO; BigDecimal prevFirstNumber = BigDecimal.ZERO; @Override public BigDecimal get() { BigDecimal result = prevFirstNumber.add(prevSecondNumber); if (Objects.equals(result, BigDecimal.ZERO)) result = BigDecimal.ONE; prevSecondNumber = prevFirstNumber; prevFirstNumber = result; return result; } }) .limit(count) .forEach(System.out::println);