I don’t know why the console print -28 instead of 233. #carloan

public class CarLoan {
public static void main(String args) {

int carLoan = 1000;
int loanLength = 3;
int interestRate = 5;
int downPayment = 2000;
if (loanLength <= 0 || loanLength <= 0) {
System.out.println("Error! You must take out a valid car");
}
else if (downPayment >= carLoan) {
System.out.println("The car can be paid in full");
} else {
int remainingBalance = carLoan - downPayment;
int months = loanLength * 12;
int monthlyBalance = remainingBalance / months;
int interest = monthlyBalance * interestRate / 100;
int monthlyPayment = monthlyBalance + interest;
System.out.println(monthlyPayment);
}
}

In the code posted, downPayment is larger than carLoan so the car would be paid in full already.
(remainingBalance would be a negative number, but that else block does not actually run, I think.)

I think the project uses simple interest instead of that compound interest formula.

but compound interest would be more realistic.

I got 239.77 for the monthly payment using compound interest (and changing some variables to be of type double instead of int).

Here’s a function for that compound interest based formula given previously:

private static double getPayment(double PV, int n, double r) {
/*
PV = loan amount (present value)
n = number of months
r = rate per month
(as a decimal, not a percent)
*/
double P; // monthly payment
if (r == 0) {
P = PV / n;
}
else {
P = r * PV / (1.0 - Math.pow(1.0 + r, -n) );
}
return P;
}