Mega Code Archive

 
Categories / Java / Development Class
 

Calculates the Greatest Common Divisor of two numbers passed into the program through command line arguments

//package numeric; /** * This class calculates the Greatest Common * Divisor of two numbers passed into the program * through command line arguments. * * @author Alex Laird * @version 1.0 * File: GCD.java * Created: Sep 2008 */ public class GCD {      /**      * Returns the Greatest Common Divisor of two      * numbers that are passed into the method.      *      * @param a the first integer for comparison.      * @param b the second integer for comparison.      * @throws NegativeNumberException if the input given is negative.      * @returns the Greatest Common Divisor.      */      public static int gcd(int a, int b) throws Exception      {          // throw an exception if the input is negative          if(a < 0 || b < 0)          {              throw new Exception("The user has entered a "                                                + "negative number.");          }           if(b == 0)                return a;           else                return gcd(b, a % b);      }      /**      * The main method from which the program executes;      * it handles all I/O and method execution.      *      * @param args Arguments received from the command line (two numbers).      * @param gcd The calcuated Greatest Common Divisor of args[0] and args [1].      */      public static void main(String[] args)      {           // ensure the user only enters two arguments           if(args.length == 2)           {                // ensure the users arguments are numbers                try                {                     // calculate gcd                     int gcd = gcd(Integer.parseInt(args[0]),                               Integer.parseInt(args[1]));                     System.out.println("The Greatest Common Divisor of "                                        + args[0] + " and " + args[1] + " is "                                        + gcd + ".");                }                catch(NumberFormatException c)                {                     System.out.println("Your arguments must be in "                                        + "the form of integers when "                                        + "running the program (ex. "                                        + "enter 'java numeric.GCD "                                        + "50 30').");                }                catch(Exception c)                {                     // used only in GUI                }           }           else           {                System.out.println("Enter two numbers as arguments "                                   + "when running the program (ex. "                                   + "enter 'java numeric.GCD 50 30').");           }      } }