Reputation: 1726
The fifteen.monthyPayment()); is returning infinity every time I run it. I cannot figure out why. I believe it has something to do with the years, because if I change the years value to equal a certain number, say 15, it does not return infinity. I thought the MyLoan fifteen should change it to 15 for me.
Can any body tell me why this code is returning infinity?
public class MyLoan {
// instance members
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
// public instance method
public MyLoan(double amt, double rt, int yrs) {
this.amountBorrowed = amt;
this.yearlyRate = rt;
this.years = yrs;
}
public double monthlyPayment() {
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * ((i * (Math.pow(1+i,n))) / ((Math.pow(1 + i, n))-1));
return A;
}
public static void main(String[] args) {
double RATE15 = 5.75;
double RATE30 = 6.25;
double amount = 10000;
}
MyLoan fifteen = new MyLoan(amount, RATE15, 15);
System.out.println(fifteen.monthlyPayment());
}
Upvotes: 0
Views: 723
Reputation: 37665
You need to initialise n
in the constructor.
this.years = yrs;
this.n = yrs * 12;
Otherwise it uses the default value for years
, which is 0
.
Division by 0
is resulting in Double.POSITIVE_INFINITY
.
Upvotes: 3