Java Fibonacci series

980 views Asked by At

What would be the next step in order to ask the user which of the numbers in this series of 30 he wants to see and prompts for an integer input - a number between 1 and 30 (inclusive)?

So if the user wants to see the fifth (5th) number of the Fibonacci series the user would input the integer 5 in response to the prompt.

public class MyFibonacci {
    public static void main(String a[]) {
         int febCount = 30;
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         for(int i=2; i < febCount; i++) {
             feb[i] = feb[i-1] + feb[i-2];
         }

         for(int i=0; i< febCount; i++) {
                 System.out.print(feb[i] + " ");
         }
    }
}   
4

There are 4 answers

0
AudioBubble On

Use a Scanner, or some InputStreamReader to read the input from the console. Scanner would be used in this way:

Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt())
    int someInt = scanner.nextInt();

Another option would be to use some reader like this:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

and parse the required data from the output of the reader. Using Scanner will be simpler in most cases though.

4
Ritesh  Karwa On

Here you go :

 public class TestProgram {

    public static void main(String a[]) {

        Scanner reader = new Scanner(System.in);
        printFibonacciSeries();
        System.out.println("");
        System.out.println("Fibonacci Series, Enter the number in the series of 30 you want to see");
        int num = reader.nextInt();
        int febCount = 30;
        int[] feb = new int[febCount];
        feb[0] = 0;
        feb[1] = 1;
        for (int i = 2; i < febCount; i++) {
            feb[i] = feb[i - 1] + feb[i - 2];

            if (i == num) {
                System.out.print(feb[i] + " ");
            }
        }
    }

    public static void printFibonacciSeries() {

        int febCount = 31;
        int[] feb = new int[febCount];
        feb[0] = 0;
        feb[1] = 1;
        for (int i = 2; i < febCount; i++) {
            feb[i] = feb[i - 1] + feb[i - 2];
            System.out.print(feb[i] + " ");

        }
    }

}
0
Adriaan Koster On

You could use a command line argument and read it from the main method args:

public class MyFibonacci {
    public static void main(String a[]) throws NumberFormatException {
         int febCount = Integer.parseInt(a[0]);

then call it with

java MyFibonacci 30

Or pass it in the 'VM options' input in an IntelliJ run configuration

1
IronFist On
public class Fibonacci_series  // upto less than a given number
{
    public static void main(long n)
    {
        long a=0, b=1, c=0;
        while (c<n)
        {
            a=b;
            b=c;
            System.out.print(c+", ");
            c=a+b;
        }
        System.out.print("....");
    }
}