/* Write a program which will keep track of a loan as you pay it off month by month. * There will be a minimum amount to pay off each month but some months you may be * able to pay more. The user will input the monthly amount until the loan is paid * in full. */ import java.util.Scanner; public class LoanPayoff { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("How much was the original loan? "); double amount = in.nextDouble(); // the amount to pay off System.out.print("How much is your interest rate on the loan (annual interest)? "); double rate = in.nextDouble(); // the interest rate applied per year, we divide this by 12 and add this to the amount each month for interest accrued double minimum, thisMonth; // minimum amount required to pay which is 5% of the total, and the amount the user is paying this month int count = 0; // count the number of months it takes to pay off the loan double totalPay=0; // the total amount paid, used to compute average monthly payments at the end while(amount > 0) // iterate until the loan is paid off { amount += amount * rate / 1200; // add interest to the amount for the current month System.out.printf("Current balance: $%8.2f\n", amount); // output current amount and minimum payment for the month minimum = .05 * amount; System.out.printf("Minimum payment: $%8.2f\n", minimum); System.out.print("How much are you paying this month? "); thisMonth = in.nextDouble(); // input the amount for the month and data verify that it is at least the minimum amount while(thisMonth < minimum) { System.out.printf("That is not enough, you must pay at least $%8.2f, try again ", minimum); thisMonth = in.nextDouble(); } if(thisMonth > amount) thisMonth = amount; // if they input a value larger than the remaining amount, we only accept the needed amount amount -= thisMonth; // deduct the payment from the remaining amount count++; // they've now made 1 more payment, add 1 to count and add this payment to their total payment totalPay += thisMonth; } double average = 0; if(count > 0) average = totalPay/count; // using the if to avoid a possible division by 0 error if there were no payments made System.out.printf("Including interest, you paid $%8.2f over %d months averaging $%8.2f per month", totalPay, count, average); } }