Skip to content

Commit 7a42f17

Browse files
committed
Refactoring Repetitive Patterns: Mortgage Calculator
1 parent d78976a commit 7a42f17

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
@@ -1,13 +1,40 @@
11
package com.avinashbest;
22

3+
import java.text.NumberFormat;
4+
import java.util.Scanner;
5+
36
public class Main {
47

58
public static void main(String[] args) {
6-
String message = greetUser("Avinash", "Kumar");
7-
System.out.println(message);
9+
int principal = (int) readNumber("Principal ($1K - $1M): ", 1000, 1_000_000);
10+
float annualInterest = (float) readNumber("Annual Interest Rate (1% - 30%): ", 1, 30);
11+
byte years = (byte) readNumber("Period (1 Years- 30 Years): ", 1, 30);
12+
13+
double mortgage = calculateMortgage(principal, annualInterest, years);
14+
System.out.println("Mortgage: " + NumberFormat.getCurrencyInstance().format(mortgage));
15+
}
16+
17+
public static double readNumber(String prompt, double min, double max) {
18+
Scanner scanner = new Scanner(System.in);
19+
double value;
20+
while (true) {
21+
System.out.print(prompt);
22+
value = scanner.nextDouble();
23+
if (value >= min && value <= max) {
24+
break;
25+
}
26+
System.out.println("Enter a value between " + min + " and " + max);
27+
}
28+
return value;
829
}
930

10-
public static String greetUser(String firstname, String lastName) {
11-
return "Hello " + firstname + " " + lastName;
31+
public static double calculateMortgage(int principal, float annualInterest, byte years) {
32+
final byte MONTHS_IN_YEAR = 12;
33+
final byte PERCENT = 100;
34+
35+
float monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;
36+
short numberOfPayments = (short) (years * MONTHS_IN_YEAR);
37+
38+
return principal * (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments) / (Math.pow(1 + monthlyInterest, numberOfPayments) - 1));
1239
}
1340
}

0 commit comments

Comments
 (0)