CH6 – One More Example

  1. Create a new class named Fibonacci.
  2. 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);
  }
}
  1. 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);
}
  1. 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);
  }
}