home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / javafile / ch02 / Ammortize.java next >
Encoding:
Java Source  |  1998-12-14  |  2.1 KB  |  72 lines

  1. import java.io.*;
  2.  
  3. /*
  4.  * Ammortize.class calculates monthly payment given
  5.  * loan amount, interest, and the number of years of the loan
  6.  */
  7. class Ammortize {
  8. public static void main (String args[]) {
  9.        double loanAmount=0, interest=0, years=0;
  10.  
  11.       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  12.  
  13.         loanAmount = inputDouble ("Enter the loan amount in dollars > ", in);
  14.  
  15.         interest = inputDouble ("Enter the interest rate in percent > ", in);
  16.  
  17.         years = inputDouble ("Enter the number of years > ", in);
  18.  
  19.         System.out.print ("The payment is $");
  20.         System.out.println (payment (loanAmount, interest, years));
  21. } // end of main ()
  22.  
  23. /*
  24.  * inputDouble method prints a prompt and reads a double
  25.  * BufferedReader 
  26. */
  27. static double inputDouble (String prompt, BufferedReader in) {
  28.         boolean error;
  29.         String input="";
  30.         double value=0;
  31.  
  32.         do {
  33.                error = false;
  34.                System.out.print (prompt);
  35.                System.out.flush ();
  36.                try {
  37.                       input = in.readLine ();
  38.                } catch (IOException e) {
  39.                       System.out.println ("An input error was caught");
  40. System.exit (1);
  41.                }
  42.                try {
  43.                      value = Double.valueOf (input).doubleValue();
  44. } catch (NumberFormatException e) {
  45.                       System.out.println ("Please try again");
  46.                       error = true;
  47.                }
  48.         } while (error);
  49.         return value;
  50. } // end of inputDouble ()
  51.  
  52. /*
  53.  * payment method does the magic calculation
  54.  *      double A      loan amount
  55.  *      double I      interest rate, as a percentage
  56.  *      double Y      number of years
  57.  */
  58. static double payment (double A, double I, double Y) {
  59.  
  60. /*
  61.  * call the exponentiation and natural log functions as
  62.  * static methods in the Math class
  63.  */
  64.         double top = A * I / 1200;
  65.         double bot = 1 - Math.exp (Y*(-12) * Math.log (1 + I/1200));
  66.  
  67.         return top / bot;
  68. } // end of payment ()
  69. }
  70.  
  71.  
  72.