- Create a new class named Fibonacci.
- Add a method named fibonacci that takes an integer as a parameter and returns an integer.
public class Fibonacci{ public static int fibonacci(int n){ if(n==1 || n==2){ return 1; } return fibonacci(n-1) + fibonacci(n-2); } }
- Create a main method and have it call the fibonacci method.
public static void main(String[] args){ int val = Integer.parseInt(args[0]); int result = Fibonacci.fibonacci(val); System.out.println(result); }
- Compile and run the program.
$ javac Fibonacci.java $ java Fibonacci 33 3524578
The complete class should appear as follows.
public class Fibonacci{ public static int fibonacci(int n){ if(n==1 || n==2){ return 1; } return fibonacci(n-1) + fibonacci(n-2); } public static void main(String[] args){ int val = Integer.parseInt(args[0]); int result = Fibonacci.fibonacci(val); System.out.println(result); } }