import java.util.Scanner; import java.util.InputMismatchException; public class Fibonacci { // prints the n-th fibonacciNumber public static int fibonacciNumber(int n) { if ( n < 1 ) { return 0; } else if ( n == 1 ) { return 1; } else { return fibonacciNumber(n-1) + fibonacciNumber(n-2); } } public static int iterativeFibonacciNumber(int n) { if ( n < 1 ) { return 0; } else if ( n == 1 ) { return 1; } int arr[] = new int[n+1]; arr[0] = 0; arr[1] = 1; for ( int i = 2; i < n+1; i++ ) { arr[i] = arr[i-1] + arr[i-2]; } return arr[arr.length - 1]; } public static void main (String[] args) { int n = 0; if ( args.length > 0 ) { try { n = Integer.parseInt(args[0]); } catch ( NumberFormatException nfe ) { // System.err.println("Invalid input."); } } if ( n == 0 ) { // either no input is given through command line, or the input was invalid. System.out.print("Enter a number, n >= 1, and I will print the n-th Fibonacci number: "); try { Scanner keyboard = new Scanner(System.in); n = keyboard.nextInt(); } catch ( InputMismatchException ime ) { System.err.println("Invalid input."); System.exit(1); } if ( n < 1 ) { System.err.println("Number must be greater than 0."); System.exit(1); } } if ( (args.length == 1 && args[0].compareTo("-i") == 0) || (args.length == 2 && args[1].compareTo("-i") == 0) ) { // iterative version is asked System.out.printf("The %d-th Fibonacci number is: %d.\n", n, iterativeFibonacciNumber(n)); } else { System.out.printf("The %d-th Fibonacci number is: %d.\n", n, fibonacciNumber(n)); } } }