CompMortgage

Updated Dani 0 Tallied Votes 215 Views Share

A simple demonstration of how MyInput.class can be used to input data from the keyboard. Computation is then done to compute the interest rate on a mortage.

package compmortgage;
public class CompMortgage {
    // Main method
    public static void main(String[] args) {
        double annualInterestRate;
        int numOfYears;
        double loanAmount;
        String prompt = "\n\nEnter yearly interest rate, for example 8.25 ";
        // Enter monthly interest rate
        System.out.println(prompt);
        annualInterestRate = MyInput.readDouble();
        while (annualInterestRate > 0) {
            // Obtain monthly interest rate
            double monthlyInterestRate = annualInterestRate / 1200;
            // Enter number of years
            System.out.println(
                "Enter number of years as an integer, for example 5: ");
            numOfYears = MyInput.readInt();
            // Enter loan amount
            System.out.println("Enter loan amount, for example 120000.95: ");
            loanAmount = MyInput.readDouble();
            // Calculate payment
            double monthlyPayment = loanAmount * monthlyInterestRate /
                (1 - (Math.pow(1 / (1 + monthlyInterestRate), numOfYears * 12)));
            double totalPayment = monthlyPayment * numOfYears * 12;
            // Display results
            System.out.println("The monthly payment is " + monthlyPayment);
            System.out.println("The total payment is " + totalPayment);
            // Enter monthly interest rate
            System.out.println(prompt + "(0 to exit) ");
            annualInterestRate = MyInput.readDouble();
        }
    }
}

Dani AI

Generated

Good, compact demo from — a nice learning example for console input and the mortgage formula. A few targeted changes will make the program safer and more useful for real use or later re-use.

First, handle the zero-interest case explicitly (the standard formula divides by zero when the monthly rate is 0). Move the math into a small, testable method and treat the zero-rate branch separately:

private static double computeMonthlyPayment(double loanAmount, double monthlyRate, int months) {
    if (months <= 0) throw new IllegalArgumentException("months must be positive");
    if (monthlyRate == 0.0) return loanAmount / months;
    return loanAmount * monthlyRate / (1 - Math.pow(1 + monthlyRate, -months));
}

Second, add input validation and robust parsing. Don’t assume MyInput will refuse bad tokens — validate that numOfYears > 0, loanAmount >= 0, and annualInterestRate >= 0 (use 0 as the sentinel to exit). Prefer Scanner or explicit try/catch around Double.parseDouble/Integer.parseInt and re-prompt users on invalid input to avoid exceptions or unexpected exits.

Third, output and numeric considerations: for a classroom demo double is fine, but for production financial calculations use BigDecimal with an explicit scale and rounding mode. At minimum format output to two decimal places so results look like currency:

System.out.printf("Monthly payment: %.2f%n", monthlyPayment);
System.out.printf("Total payment: %.2f%n", totalPayment);

Finally, separate I/O from computation so the calculation can be unit-tested and reused; add guard clauses for invalid inputs; and document the assumption that the annual rate is a percentage (e.g., 8.25 means 8.25%). As suggested, this is a great base to continue from — modularize the logic, add validation, and you’ll have a small, reliable mortgage utility.

holmes008 0 Light Poster

I Hope You Will Continue this!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.