package com.evanhoffman.interest; import java.text.DecimalFormat; import java.text.NumberFormat; public class InterestCalculator { static final NumberFormat df = new DecimalFormat("##0.00"); static double getAmountWithInterest(double initialPrincipal, double interestRate, int periodsPerYear, int totalYears) { double p = initialPrincipal * Math.pow((1 + (interestRate / periodsPerYear)),(periodsPerYear*totalYears)); return p; } static double getAmountWithContinuouslyCompoundedInterest(double initialPrincipal, double interestRate, int totalYears) { double p = initialPrincipal * Math.pow(Math.E,(interestRate *totalYears)); return p; } static void printAmountWithInterest(double initialPrincipal, double interestRate, int periodsPerYear, int totalYears, double annualAddition) { double v = initialPrincipal; double periodicRate = interestRate / periodsPerYear; for (int currentYear = 1; currentYear <= totalYears; currentYear++) { System.out.println("Starting year "+currentYear+" with $"+df.format(v)); for (int currentPeriod = 1; currentPeriod <= periodsPerYear; currentPeriod++) { double periodInterest = v * periodicRate; v = v + periodInterest; System.out.println("Year "+currentYear+", period "+currentPeriod+", accrued $"+df.format(periodInterest)+", value is now: $"+df.format(v)); } v += annualAddition; System.out.println("Added $"+df.format(annualAddition)+" for the end of year "+currentYear+", total is now: "+df.format(v)); } System.out.println("Final value: $"+df.format(v)); // double p = initialPrincipal * Math.pow((1 + (interestRate / periodsPerYear)),(periodsPerYear*totalYears)); } static final int pIndex = 0; static final int rIndex = 1; static final int nIndex = 2; static final int tIndex = 3; static final int aIndex = 4; public static void main(String args[]) { double p = Double.parseDouble(args[pIndex]); double r = Double.parseDouble(args[rIndex]); int n = Integer.parseInt(args[nIndex]); int t = Integer.parseInt(args[tIndex]); double a = Double.parseDouble(args[aIndex]); System.out.println("Initial principal: "+df.format(p)); System.out.println("Interest rate: "+df.format(r)+" ("+df.format(r*100)+"%)"); System.out.println("# of ann. periods: "+n); System.out.println("Total years: "+t); System.out.println("Annual Addition: "+a); // System.out.println("Total with finite compounding: "+df.format(getAmountWithInterest(p, r, n, t))); // System.out.println("Total with continuous compounding: "+df.format(getAmountWithContinuouslyCompoundedInterest(p, r, t))); printAmountWithInterest(p, r, n, t, a); } }