简体   繁体   中英

Java my loan class formula is returning infinity

I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.

public class MyLoan
{

private double amountBorrowed;
private double yearlyRate;
private int years;

public double A;
public double n = years * 12;

public MyLoan(double amt, double rt, int yrs)
{
    amountBorrowed = amt;
    yearlyRate = rt;
    years = yrs;
}
public double getAmountBorrowed()
{
    return amountBorrowed;
}

public double getYearlyRate()
{
    return yearlyRate;
}

public int getYears()
{
    return years;
}

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 double totalPayment()
{
    return A * (years * 12);
}

public String toString()
{
    return "Loan: " +  "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}



public static void main(String[] args)
{

final double RATE15 = 5.75;
final double RATE30 = 6.25;


StdOut.println("***** Welcome to the Loan analyzer! *****");

String ans = "Y";

do {
  StdOut.print("\n  Enter the principle amount to borrow: ");
  double amount = StdIn.readDouble();


  MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
  MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);

  double amount15 = fifteenYears.monthlyPayment();
  double total15 = fifteenYears.totalPayment();
  double amount30 = thirtyYears.monthlyPayment();
  double total30 = thirtyYears.totalPayment();

  StdOut.println("===========ANALYSES==========");
  StdOut.println(fifteenYears);
  StdOut.println("Monthly payment = " + "$" + amount15);
  StdOut.println("Total payment = " + "$" + total15);

  StdOut.println("");
  StdOut.println("");

  StdOut.println(thirtyYears);
  StdOut.println("Monthly payment = " + "$" + amount30);
  StdOut.println("Total payment = " + "$" + total30);
  StdOut.println("=============================");



  StdOut.print("\n      ** Do you want to continue (y/n)? ");
  ans = StdIn.readString();


} while (ans.toUpperCase().equals("Y"));

StdOut.println("\n********** Thank you. Come again! **********");

} 

}

有很多计算兴趣的方法,最常见的是

A = amountBorrowed * (yearlyRate / 100) / 12;

You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM