/* Programmer: Chris Gountanis Date: 02/08/2008 Program Name: LoanCalculator.java for Week 3 IA Description: Program asks user for input amount of the loan, the interest rate and the number of years. The program validates the input checking for valid numeric data before continuing. If the interest rate was entered in percentage form it converts to decimal before calculation process. The program then calculates the monthly payment. Input values and payment total are displayed rounded to the second decimal place. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LoanCalculator { public static void main(String[] args) throws IOException { //declarations BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); double payment=0, interestrate=0, loanamount=0, years=0; String inputvalue=""; //get input for loan amount while (!isNumeric(inputvalue)) { System.out.println("Loan Amount? "); inputvalue = dataIn.readLine(); } loanamount = Float.parseFloat(inputvalue); //get input for interest rate inputvalue=""; while (!isNumeric(inputvalue)) { System.out.println("What is the Annual Interest Rate? "); inputvalue = dataIn.readLine(); } interestrate = Float.parseFloat(inputvalue); //get input for the number of years inputvalue=""; while (!isNumeric(inputvalue)) { System.out.println("How many Years? "); inputvalue = dataIn.readLine(); } years = Float.parseFloat(inputvalue); //if the interest rate was entered in as percentage convert to decimal if (interestrate > 1) { interestrate = interestrate / 100; } //calculate the monthly payment total payment = (interestrate * loanamount / 12) / (1.0 - Math.pow(((interestrate / 12) + 1.0), (-(12 * years)))); //output the total and input values System.out.print("\nThe Loan Amount:\t\t$" + loanamount); System.out.print("\nThe Interest Rate:\t\t" + Round(interestrate * 100, 2) + "%"); System.out.print("\nThe Number of Years:\t\t" + years + " (Months: " + years * 12 + ")"); System.out.print("\n\nThe Monthly Payment:\t\t$" + Round(payment, 2)); } //used to validate for numeric data private static boolean isNumeric(String str){ try { Float.parseFloat(str); return true; } catch (NumberFormatException nfe){ return false; } } //used to round to a certain number of decimal places public static float Round(double Rval, int Rpl) { float p = (float)Math.pow(10, Rpl); Rval = Rval * p; float tmp = Math.round(Rval); return (float)tmp/p; } }