|
1 | 1 | package com.avinashbest;
|
2 | 2 |
|
| 3 | +import java.text.NumberFormat; |
| 4 | +import java.util.Scanner; |
| 5 | + |
3 | 6 | public class Main {
|
4 | 7 |
|
5 | 8 | 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; |
8 | 29 | }
|
9 | 30 |
|
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)); |
12 | 39 | }
|
13 | 40 | }
|
0 commit comments