Sample Code For Project 2

[Kathy's Code] [Zak's Code] [Rob's Code]

//Judy's code
public class Mortgage {
   public static void main (String[] args){
       double payment, principal = 80000;
       double annualInterest = .065;
       int years = 15;
        
       if (args.length == 3) {
           try {
               principal = Double.parseDouble(args[0]);
               annualInterest = Double.parseDouble(args[1]);
               years = Integer.parseInt(args[2]);
           }
           catch (Exception e) {
               System.out.println("Wrong input " + e.getMessage() );
               System.exit(0);
           }
           print(principal, annualInterest, years);
        }else if(args.length == 0) {
           //print(principal, annualInterest, years);
           getUserInput();    
        } else {
           System.out.println("Usage: java Mortgage principal annualInterest years ");
           System.exit(0);
        }
   }
  /*
   * calculates a monthly payment given
   * a principal, annual interest rate and term
   */
   public static double calcPayment(double pr, double annRate, int years){
       double monthlyInt = annRate / 12;
       double monthlyPayment = (pr * monthlyInt)
                    / (1 - Math.pow(1/ (1 + monthlyInt), years * 12));
       return Judy.format(monthlyPayment, 2);
   }
    
   public static void print(double pr, double annRate, int years){
       double mpayment = calcPayment(pr, annRate, years);
       System.out.println("The principle is $" + (int)pr);
       System.out.println("The annual interest rate is " + Judy.format(annRate * 100, 2) +"%");
       System.out.println("The term is " + years + " years");
       System.out.println("Your monthly payment is $" + mpayment);
   }
    
   public static void print(double payment) {
       payment = Judy.format(payment, 2);// print payment or interest rate if needed
       System.out.println("Your monthly payment is $" + payment);
   }
   
   //accept user input  
   public static void getUserInput() {
       double principal = 0.0;
       double annuRate = 0.0;
       int years = 0;
       char ch = 'y';
       while(true) {
           System.out.print("\nPlease enter the principal: $" );
           try {
               principal = Judy.readDouble();
           }catch(Exception e) {
               System.out.println("Exception: " + e.getMessage());
           }
           System.out.print("Please enter the annual interest rate: " );
           try {
               annuRate = Judy.readDouble();
           }catch(Exception e) {
               System.out.println("Exception: " + e.getMessage());
           }
           System.out.print("Please enter payment term: " );
           try {
               years = Judy.readInt();
           }catch(Exception e) {
               System.out.println("Exception: " + e.getMessage());
           }
           double payment = calcPayment(principal, annuRate, years);
           print(payment);
          
           System.out.print("\nDo you want to continue yes/no ? ");
          
           try {
               ch = Judy.readChar();
               ch = Character.toLowerCase(ch);
           }catch(Exception e) {
               System.out.println(e.getMessage());
           }
           if (ch =='n')
               System.exit(0);
       }
   }
}

Return to top


//Author: Kathy Gerlach
public class Mortgage {

   static Kathy kg = new Kathy();
   
   public static void main (String[] args) {
        
       double principle = 80000;
       double annualInterest = .065;
       int years = 15;   
       int inputargs = 0;
       boolean playagain = true;
 
       inputargs = args.length;     // Determine number of arguments entered on command line
       switch (inputargs)
       {
         case 0:                   // None entered  Method 3 
           do {
             principle = getPrinciple();
             annualInterest = formatInterest(getInterest());
             years = getYears();
             display (calcPayment(principle, annualInterest, years));
             playagain = getUserchoice();

           } while (playagain); 
             System.exit(0);   
        
         case 3:                  // Values entered on command line  Method 2
         try {
              principle = Double.parseDouble(args[0]);
              annualInterest = formatInterest(Double.parseDouble(args[1]));
              years = Integer.parseInt(args[2]);
           } catch(Exception e) {
              System.out.println("Incorrect input: " + e.getMessage());
              System.out.println("Please try again.");
              System.exit(1);
           }
              if (principle > 0  &&
                  annualInterest > 0 &&
                  years > 0)
                    display(principle, annualInterest, years, calcPayment(principle, annualInterest, years));
              else
                    System.out.println("Enter values greater than zero");
               
             System.exit(0);       

         default:
             System.out.println("Missing input data, please try again. ");
             System.out.println("Correct input is Principle Interest Term");
             System.exit(1);

       }   // end of switch 

    }   //  end of main() 

/*   This method will request user to enter a principle amount
     and will retrieve the amount entered by the user */

  public static double getPrinciple()   {

     double temp = 0;
     boolean right = true;  

     while (true) {
        right = true;
        System.out.print("Please enter the principle: $");
        try {
            temp = kg.readDouble();
        } catch(Exception e) {           // Check for numeric amount
            System.out.println("Enter a numeric amount, please");
            right = false;
        }
 
        if (right) {
           if (temp > 0) {                // Check for amount > zero
             break;
           }
           else  {
             System.out.println("Enter an amount greater than zero, please");
           }
        }
     }    //  End while loop for Principle amount 
  
     return temp;         //  Return entered principle amount
 
   }  //  End of getPrinciple


/*   This method will request user to enter an interest amount
     and will retrieve the interest rate entered by the user */

   public static double getInterest()   {

      double temp = 0;
      boolean right = true;  

       while (true) {
           right = true;
           System.out.print("Please enter the annual interest rate: ");
           try {
               temp = kg.readDouble();
           } catch(Exception e) {               // Check for numeric amount
           System.out.println("Enter an interest rate, please");
           right = false;
           }

           if (right) {
              if (temp > 0) {                   // Check for amount > zero
              break;
           }
           else  {
               System.out.println("Enter a rate greater than zero, please");
           }
         }
       }   // End while loop for interest amount
        return temp;     //Return entered interest rate
   }   // End of getInterest

/*   This method will request user to enter term years
     and will retrieve the years entered by the user */

   public static int getYears()   {

       int temp = 0;
       boolean right = true;  

       while (true) {
           right = true;
           System.out.print("Please enter the payment term: ");
           try {
              temp =kg.readInt();
           } catch(Exception e) {             // Check for numeric amount
              System.out.println("Enter a numeric payment term please");
              right = false;
           }
       
           if (right) {
               if (temp > 0) {                // Check for amount > zero
                   break;
               }
               else  {
                 System.out.println("Enter a term greater than zero, please");
               }
           }
       }  //  end while loop for term 
 
        return temp;                    //  Return entered years

    }  //  End of getYears


/*   This method will request user to continue or end
     and will retrieve the value entered by the user */

    public static boolean getUserchoice() {
    
       String select = "";
       char selectc = ' '; 
       boolean choice = true;
       boolean invalidchoice = false;   // Used for validity check of user response

      do {
           System.out.print("\nDo you want to continue yes/no ?");
           try {
               select = kg.readString();
               selectc = select.charAt(0);   
               selectc = Character.toLowerCase(selectc);
           } catch(Exception e) {
               invalidchoice = true;
           }
           if (selectc =='n') {
               invalidchoice = false;
                choice = false;
           }
           else {
               if (selectc == 'y') {
                   invalidchoice = false;
               }
               else {
                   invalidchoice = true;
                   System.out.println("Invalid response, please enter y or n");
               }
           }
       }  while (invalidchoice);
       return choice;
   }


/*   This method will format the interest rate entered
     to its decimal equivalent */

   public static double formatInterest(double interest){
       if (interest > 1) 
           interest = interest / 100;
       return interest;
   }


   /* 
    * calculates a monthly payment given
    * a principal, annual interest rate and term
    */
   public static double calcPayment(double pr, double annRate, int years){
       double monthlyInt = annRate / 12;
       double monthlyPayment = (pr * monthlyInt)
             / (1 - Math.pow(1/ (1 + monthlyInt), years * 12));
       return monthlyPayment;
   }


   /* 
    * Display monthly payment amount
    */

   public static void display(double mpay) {
       String msg = ("Your monthly payment is $" + kg.format(mpay,2)); 
       System.out.println(msg);
  
   }  


    /* 
     * Display the principle
     * Display the interest rate
     * Display the term
     * Display monthly payment amount
     */

   public static void display(double prin, double Rate, int years, double mpay) {
       String msg = ("The principle is $" + (long)prin +  "\nThe annual interest rate is " 
                  +  kg.format((Rate * 100),2) + "%" 
                  +  "\nThe term is " + years + " years" 
                  +  "\nYour monthly payment is $" + kg.format(mpay,2)); 
       System.out.println(msg);
   }
} //  End of Mortgage class

Return to top


//Author: Zak Anderson
public class Mortgage{
    
    private double payment;
    private double principle;
    private double annualInterest;
    private int years;
    
    /** 
     *Constructor with default values
     */
    public Mortgage(){
        principle = 80000;
        annualInterest = .065;
        years = 15;
        payment = calcPayment(principle, annualInterest, years);
    }
    
    /**
     *Constructor with user values
     */
     
    public Mortgage(double pr, double annRate, int yrs){
        principle = pr;
        annualInterest = annRate;
        years = yrs;
        payment = calcPayment(principle, annualInterest, years);
    }
    
    /** 
     *Entry point for program
     *Handles commandline arguements
     *No arguements will provide interactive entry mode and will allow for multiple calculations
     *Three arguements will set properties of the Mortgage object and display results
     *Invalid arguements will result in display of usage and example information
     */
    public static void main(String[] args) {
        // User provided no commandline arguements, do interactive mode
        if (args.length == 0) {
            char ContinueResponse = 'N'; // default to not continue
            do {
                try {
                    Mortgage myMortgage = new Mortgage(inputPrinciple(), inputInterestRate(), inputPaymentTerm());
                    System.out.println(myMortgage);
                }
                catch (Exception e) {
                    System.out.println("Error processing Mortgage information.");
                    System.exit(1);
                }
                try {
                    ContinueResponse = inputContinueResponse();
                }
                catch (Exception e){
                    System.out.println("Error reading response, exiting...");
                    System.exit(1);
                }
            } while(('Y' == ContinueResponse)||('y'== ContinueResponse));
            System.exit(0);
        }
        // User supplied three command line arguements, process them if possible
        else if (args.length == 3) {
            try {
                Mortgage myMortgage = new Mortgage(Double.parseDouble(args[0]), Double.parseDouble(args[1]), Integer.parseInt(args[2]));
                System.out.println(myMortgage);
                System.exit(0);
            }
            catch (Exception e){
                System.out.println("Error processing Mortgage information.");
                System.exit(1);
            }
        }
        // User supplied invalid number or type of arguements, display usage and example
        else {
            Mortgage myMortgage = new Mortgage();
            System.out.println("Usage: Mortgage [Principle] [Interest Rate] [Payment Term]");
            System.out.println("(All values must be greater than zero)");
            System.out.println("Example: Mortgage 80000 .065 15");
            System.out.println(myMortgage);
            System.exit(0);
        }
    }
    
    /** 
     *Overridden method toString will return a string containing the important
     *information about an instance of this class
     */
    public String toString(){
        String output = ("\nThe principle is: $" + (int)principle);
        output += ("\nThe annual interest rate is: " + Zak.format((annualInterest * 100),3) + "%");
        output += ("\nThe term is " + years + " years.");
        output += ("\nYour monthly payment is $" + Zak.format(payment,2));
        return output;
    }
    
    /**
     *Simple payment calculation based on principle, interest rate and term
     */
    public static double calcPayment(double pr, double annRate, int years) {
        double monthlyInt = (annRate / 12);
        double monthlyPayment = ((pr * monthlyInt) / (1 - Math.pow(1/ (1 + monthlyInt), years * 12)));
        return monthlyPayment;
    }
    
    /**
     *Calls an externally defined method to input a double for the Principle
     */
    public static double inputPrinciple() throws Exception{
        System.out.print("Please enter the principle: $");
        int principle = Zak.readInt();
        if (principle <= 0)
        {
           OutOfValidRangeInputException e = new OutOfValidRangeInputException();
           throw e;
        }
        else
        {
            return principle;
        }
    }
    
    /**
     *Calls an externally defined method to input a double for the Interest Rate
     */
    public static double inputInterestRate() throws Exception{
        System.out.print("Please enter the annual interest rate: ");
        double interestRate = Zak.readDouble();
        if (interestRate <= 0)
        {
            OutOfValidRangeInputException e = new OutOfValidRangeInputException();
            throw e;
        }
        else
        {
            return interestRate;
        }
    }
    
    /**
     *Calls an externally defined method to input an int for the payment term
     */
    public static int inputPaymentTerm() throws Exception{
        System.out.print("Please enter the payment term: ");
        int paymentTerm = Zak.readInt();
        if (paymentTerm <= 0)
        {
           OutOfValidRangeInputException e = new OutOfValidRangeInputException();
           throw e;
        }
        else
        {
           return paymentTerm;
        }
    }
    
    /**
     *Asks the user if they wish to continue and returns a character for the response
     */
    public static char inputContinueResponse() throws Exception{
        System.out.print("\nDo you want to continue yes/no ? ");
        return Zak.readChar();
    }
}
//OutOfValidRangeInputException.java
public class OutOfValidRangeInputException extends Exception{
        public OutOfValidRangeInputException(){}
}

Return to top


//Author: Rob Dills
public class Mortgage {

/*=====================================================================
*    main(): throws Exception, if wrong number of arg passed          *
*    Main will take 0 or 3 arg from the command line.                 *
*    Program will run until user quits.                               *
*====================================================================*/ 

   public static void main (String[] args) throws Exception
   {
       boolean done = false;
       double payment=0.0;
       double principal = 80000.00;
       double annualInterest = .065;
       int years = 15;
       char ch = 'x';

       if (args.length == 3)
       {
          String[] strInput = {args[0], args[1], args[2]};
          calcCmdline(strInput);
       }
       else
       {
          if (!(args.length == 0))
          {
             System.out.print("\n   INPUT ERROR: Wrong Number of Args Entered!");
             System.exit(0);
          }
          else  
          {
             // part 3, remove this else block to run part 1.
             do
             {
                 principal = getPrincipal();
                 annualInterest = getInterest();
                 years = getYears();
                 payment = calcPayment(principal, annualInterest, years);
                 display(principal, annualInterest, years, payment);
                 System.out.print("\n");
                 do
                 {
                    System.out.print("Do you want to calculate another payment, Yes or No?");
                    try
                    {
                       ch = Rob.readChar();
                    }
                    catch(Exception err) {}
                    ch = Character.toLowerCase(ch);
                    switch(ch) 
                    {
                       case 'n':
                          done = true;
                       case 'y':
                          break;
                    } //end of switch   
                 }while(!(ch=='y'||ch=='n'));
             }while(!done);
          }
       }
   }


/*=====================================================================
*    calcCmdline: throws Exception, if wrong data type from user      *
*====================================================================*/ 

   public static void calcCmdline(String str[]) throws Exception
   {    
       boolean valid = true;
       double payment=0.0;
       double principal = 80000.00;
       double annualInterest = .065;
       int years = 15;

  // test input Double
       try
       {
          principal = Math.abs(Double.parseDouble(str[0]));
       }
       catch(NumberFormatException err)
       {
          System.out.println("  INVALID INPUT ==> first value is NOT a Dollar Amount!");
          valid = false;
       }

  // test input Double
       try
       {
          annualInterest = Math.abs(Double.parseDouble(str[1]));
       }
       catch(NumberFormatException err)
       {
          System.out.println("  INVALID INPUT ==> second value is NOT a Percentage!");
          valid = false;
       }

  // test input Integer
       try
       {
          years = Math.abs(Integer.parseInt(str[2]));
       }
       catch(NumberFormatException err)
       {
          System.out.println("  INVALID INPUT ==> third value is NOT a year!");
          valid = false;
       }

  // if valid input display results, else print all errors and end program
       if (valid)
       {
          payment = calcPayment(principal, annualInterest, years);
          display(principal, annualInterest, years, payment);
       }
       else
       {
          System.exit(0);
       }
   }


/*=====================================================================
*    getPrincipal: throws Exception, if user enters wrong data type   *
*====================================================================*/

   public static double getPrincipal() throws Exception
   {    
       double input = 0;    
       boolean valid = false;
  // prompt user for input until validate datatype is entered
       while(!valid)
       {
          System.out.print("Enter Principal Amount: ");
  // test input Double
          try
          {
              input = Math.abs(Rob.readDouble());
              valid = true;
          }
          catch(NumberFormatException err)
          {
              System.out.println("  INVALID INPUT ==> NOT a Dollar Amount!");
          }
       }
       return input;
   }


/*=====================================================================
*    getInerest: throws Exception, if user enters wrong data type     *
*====================================================================*/

   public static double getInterest() throws Exception
   {    
       double input = 0;    
       boolean valid = false;
  // prompt user for input until validate datatype is entered
       while(!valid)
       {
          System.out.print("Enter the Annual Interest: ");
  // test input Double
          try
          {
              input = Math.abs(Rob.readDouble());
              valid = true;
          }
          catch(NumberFormatException err)
          {
              System.out.println("  INVALID INPUT ==> NOT a Percentage!");
          }
       }
       return input;
   }


/*=====================================================================
*    getYears: throws Exception, if user enters wrong data type       *
*====================================================================*/

   public static int getYears() throws Exception
   {    
       int input = 0;    
       boolean valid = false;
  // prompt user for input until validate datatype is entered
       while(!valid)
       {
          System.out.print("Enter number of Years: ");
  // test input Integer
          try
          {
              input = Math.abs(Rob.readInt());
              valid = true;
          }
          catch(NumberFormatException err)
          {
              System.out.println("  INVALID INPUT ==> NOT a year!");
          }
       }
       return input;
   }


/*=====================================================================
*  calcPayment: 3 args, calculates and returns a monthly payment      *  
*====================================================================*/
   
   public static double calcPayment(double pr, double annRate, int years)
   {        
       double monthlyInt = annRate / 12;
       double monthlyPayment = (pr * monthlyInt)/(1 - Math.pow(1/ (1 + monthlyInt), years * 12));
       return monthlyPayment;       
   }


/*=====================================================================
*  display: formats and displays the output                           *
*====================================================================*/

   public static void display(double disPrincipal, double disRate, int disYears, double disPayment)
   {        
       System.out.println("\nThe principle is $" + (int)disPrincipal);
       if (disRate < 1)
       {
           disRate = disRate * 100;
       }
       System.out.println("The annual interest rate is " + Rob.format(disRate, 1) + "%");
       System.out.println("The term is " + disYears + " years");
       System.out.println("Your monthly payment is $" + Rob.format(disPayment, 2));
   }  
}

Return to top