Skip to content

Commit 0c03a41

Browse files
committed
Completed: Mortgage Calculator
1 parent 7a42f17 commit 0c03a41

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

Main.java

+31-4
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,35 @@
44
import java.util.Scanner;
55

66
public class Main {
7+
final static byte MONTHS_IN_YEAR = 12;
8+
final static byte PERCENT = 100;
79

810
public static void main(String[] args) {
911
int principal = (int) readNumber("Principal ($1K - $1M): ", 1000, 1_000_000);
1012
float annualInterest = (float) readNumber("Annual Interest Rate (1% - 30%): ", 1, 30);
1113
byte years = (byte) readNumber("Period (1 Years- 30 Years): ", 1, 30);
1214

15+
printMortgage(principal, annualInterest, years);
16+
17+
printPaymentSchedule(principal, annualInterest, years);
18+
}
19+
20+
private static void printPaymentSchedule(int principal, float annualInterest, byte years) {
21+
System.out.println();
22+
System.out.println("PAYMENTS SCHEDULE:");
23+
System.out.println("------------------");
24+
for (short month = 1; month <= years * MONTHS_IN_YEAR; month++) {
25+
double balance = calculateBalance(principal, annualInterest, years, month);
26+
System.out.println(NumberFormat.getCurrencyInstance().format(balance));
27+
}
28+
}
29+
30+
private static void printMortgage(int principal, float annualInterest, byte years) {
31+
System.out.println();
32+
System.out.println("MORTGAGE");
33+
System.out.println("--------");
1334
double mortgage = calculateMortgage(principal, annualInterest, years);
14-
System.out.println("Mortgage: " + NumberFormat.getCurrencyInstance().format(mortgage));
35+
System.out.println("Monthly Payments: " + NumberFormat.getCurrencyInstance().format(mortgage));
1536
}
1637

1738
public static double readNumber(String prompt, double min, double max) {
@@ -28,10 +49,16 @@ public static double readNumber(String prompt, double min, double max) {
2849
return value;
2950
}
3051

31-
public static double calculateMortgage(int principal, float annualInterest, byte years) {
32-
final byte MONTHS_IN_YEAR = 12;
33-
final byte PERCENT = 100;
52+
public static double calculateBalance(int principal, float annualInterest, byte years, short numberOfPaymentsMade) {
53+
float monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;
54+
short numberOfPayments = (short) (years * MONTHS_IN_YEAR);
55+
56+
double balance = principal * (Math.pow(1 + monthlyInterest, numberOfPayments) - Math.pow(1 + monthlyInterest, numberOfPaymentsMade)) / (Math.pow(1 + monthlyInterest, numberOfPayments) - 1);
3457

58+
return balance;
59+
}
60+
61+
public static double calculateMortgage(int principal, float annualInterest, byte years) {
3562
float monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;
3663
short numberOfPayments = (short) (years * MONTHS_IN_YEAR);
3764

0 commit comments

Comments
 (0)