Hey there!

I was doing the Mortgage Calculator as in the java courses with Mosh are explained. However, I didn’t quite get one part. Where’s the numberOfPaymentsMade variable specified? I’ve been trying to figure that out but I actually can’t. Any ideas to specify a value to that variable?

Edit: I just checked by debugging… the numerOfPaymentsMade actually gives the correct value. Now, I wanna know why is that? And just to be sure, does it have any issues or flaws?

package me.oriol;

import java.text.NumberFormat;

import java.util.Scanner;

public class Main {

final static byte MONTHS_IN_YEAR = 12;

final static byte PERCENT = 100;

```
public static void main(String[] args) {
int principal = (int) readNumber("Principal", 1000, 1_000_000);
float annualInterest = (float) readNumber("Annual Interest Rate", 0.1F, 30);
byte years = (byte) readNumber("Period (Years)", 1, 30);
printMortgage(principal, annualInterest, years);
printPaymentSchedule(principal, annualInterest, years);
}
public static void printMortgage(int principal, float annualInterest, byte years) {
double mortgage = calculateMortgage(principal, annualInterest, years);
String mortgageCurrency = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("\nMORTGAGE" + "\n--------" + "\nMonthly Payments: " + mortgageCurrency + "\n");
}
public static void printPaymentSchedule(int principal, float annualInterest, byte years) {
System.out.println("PAYMENT SCHEDULE" + "\n----------------");
for (short month = 1; month <= years * MONTHS_IN_YEAR; month++) {
double balance = calculateBalance(principal, annualInterest, years, month);
System.out.println(NumberFormat.getCurrencyInstance().format(balance));
}
}
public static double readNumber(String prompt, float min, int max) {
Scanner scanner = new Scanner(System.in);
float value;
while (true) {
System.out.print(prompt + ": ");
value = scanner.nextFloat();
if (value >= min && value <= max)
break;
System.out.println("Enter a number between " + (short) min + " and " + max + ".");
}
return value;
}
public static double calculateBalance(int principal, float annualInterest, byte years, short numberOfPaymentsMade) {
float monthlyInterest = annualInterest / MONTHS_IN_YEAR / PERCENT;
short numberOfPayments = (short)(years * MONTHS_IN_YEAR);
return principal
* (Math.pow(1 + monthlyInterest, numberOfPayments) - Math.pow(1 + monthlyInterest, numberOfPaymentsMade))
/ (Math.pow(1 + monthlyInterest, numberOfPayments) - 1);
}
public static double calculateMortgage (int principal, float annualInterest, byte years) {
float monthlyInterest = annualInterest / MONTHS_IN_YEAR / PERCENT;
short numberOfPayments = (short)(years * MONTHS_IN_YEAR);
return principal
* (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments)
/ (Math.pow(1 + monthlyInterest, numberOfPayments) - 1));
}
```

}