- Create a new class named Factorial.
- Add the method factorial.
public class Factorial{ public static int factorial(int n){ if(n==0){ return 1; } int recurse = factorial(n-1); int result = n * recurse; return result; } }
- Add a main method and have it call the factorial method.
public static void main(String[] args){ int value = Integer.parseInt(args[0]); int factValue = Factorial.factorial(value); System.out.println("factorial of " + value + " is " + factValue); }
- Compile and run the program.
$ javac Factorial.java $ java Factorial 12 factorial of 12 is 479001600
The complete class should appear as follows.
public class Factorial{ public static int factorial(int n){ if(n==0){ return 1; } int recurse = factorial(n-1); int result = n * recurse; return result; } public static void main(String[] args){ int value = Integer.parseInt(args[0]); int factValue = Factorial.factorial(value); System.out.println("factorial of " + value + " is " + factValue); } }