Car loan project

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.)

Should all the variables be int?

Yes i followed the instruccions of the project :pleading_face:

Can you post a link to the lesson, please?


But are you sure the values for carLoan and downPayment shouldn’t be reversed?

1 Like

I took a look at the instructions for the project and you seem to have a typo at the beginning:

int carLoan = 1000;
should be
int carLoan = 10000;

2 Likes

Omg thank you so much :joy::rofl:i feel so stupid rn

Resolved already!!
It was 10000 not 1000😂thank youuuu

1 Like

Off topic

While we’re following the instructions of how to build code for this purpose, let’s also look at the math we’re aiming to emulate…

loan_payment_formula

Relate all the steps in the code to the formula above and Bob’s your uncle.

1 Like

Thank you. Actually I’m so interested in truly know the fundamentals, and really understand what I’m doing

1 Like

r is the only variable that needs clarification. ‘rate per period’. This requires background information, namely Annual Interest Rate, and Period.

Given an annual rate, R, with period, P, gives, r = R / P.

R = 12
P = 12
r = 1 / 100
1 Like

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;
  }
2 Likes