Mega Code Archive

 
Categories / Java / Development Class
 

This class calculates the Factorial of a numbers passed into the program through command line arguments

//package numeric; /** * This class calculates the Factorial of a * numbers passed into the program through * command line arguments. * * @author Alex Laird * @version 1.0 * File: Factorial.java * Created: Sep 2008 */ public class Factorial {      /**      * Returns the Factorial of a number that      * is passed into the method through command      * line arguments.      *      * @param a The counting variable and initial condition for the Factorial.      * @param factorial The running value of the Factorial.      * @throws NegativeNumberException if the input given is negative.      * @returns the calculated Factorial.      */      public static double calcFactorial(int a) throws Exception      {           double factorial = a;           // throw an exception if the input is negative           if(a < 0)           {               throw new Exception("The user has entered a "                                                 + "negative number.");           }           for(int i = (a - 1); i > 1; i--)                factorial *= i;           return factorial;      }      /**      * The main method from which the program executes;      * it handles all I/O and method execution.      *      * @param args Arguments received from the command line (one number).      * @param factorial The calculated Factorial of args[0].      */      public static void main(String[] args)      {           // ensure the user only enters one argument           if(args.length == 1)           {                // ensure the users argument is a number                try                {                     // calculate factorial                     double factorial = calcFactorial(Integer.parseInt(args[0]));                     System.out.println("The Factorial of " + args[0] + " is "                                        + factorial + ".");                }                catch(NumberFormatException c)                {                     System.out.println("Your argument must be in "                                        + "the form of an integer when "                                        + "running the program (ex. "                                        + "enter 'java numeric."                                        + "Factorial 5').");                }                catch(Exception c)                {                    // used only in GUI                }           }           else           {                System.out.println("Enter one number as an argument "                                   + "when running the program (ex. "                                   + "enter 'java numeric.Factorial 5').");           }      } }