not sure why this isn’t working. I know this is probably basic and I am pathetic at this but can anyone shed any light?
Code:
public class CarLoan {
int carLoan;
double interestRate;
int lengthOfLoan;
int downPayment;
public CarLoan(int loanAmount, double intRate, int lol, int dp) {
loanAmount = carLoan;
intRate = interestRate;
lol = lengthOfLoan;
dp = downPayment;
}
public void totalLoan() {
int totalLoan = (carLoan / interestRate) += carLoan;
System.out.println("The total amount you have loaned is:" + totalLoan);
}
public static void main(String[] args) {
CarLoan carL1 = new CarLoan(6500, 12.5, 3, 0);
carL1.totalLoan();
}
}
I am getting the error:
CarLoan.java:15: error: unexpected type
int totalLoan = (carLoan / interestRate) += carLoan;
^
required: variable
found: value
1 error
I tried a few things to rectify:
- Reversed the constructor and instance variables
- Defined the totalLoan method without a creating new variable (example: (carloan / interestRate) += carLoan)
- Tried introducing a "int" return type to the totalLoan method but I was working with a few varTypes.
>Solution :
Let’s break down the problems with the
int totalLoan = (carLoan / interestRate) += carLoan;
line. First of all, the +=
operator is adding and assigning to a variable. For example, if you have
foo += bar;
then the value of foo + bar
is computed and the result is assigned to foo
as its new value. However, your code assigns (carLoan / interestRate)
to totalLoan
, resulting in the expected value that is assigned and then you try to add carLoan
to this value and assign to the value rather than the variable. Secondly, you are computing the division of an int
and a double
, which leads to data loss if you want to assign it to an int. A possible solution would be:
int totalLoan = (int) ((carLoan / interestRate) + carLoan);
or even:
int totalLoan = (int) ((carLoan * (1 + interestRate)) / interestRate);