简体   繁体   中英

Loan calculator compound interest java

double a = Double.parseDouble(amount.getText());
double r = Double.parseDouble(rate.getText())/100;
double y = Double.parseDouble(years.getText());
double m=y*12;
double simple =a+(a*r*y);
double compound = a * Math.pow(1+ r, m);
String d = String.format("%.2f", simple);
String d1 = String.format("%.2f", simple/12);
String d2 = String.format("%.2f", compound);
int x=1;

while(x<=m && type.getSelectedItem().equals("Simple")) {
     monthly1.append(String.valueOf(x+(". ")+d1+("\n"))); 
     x++;
     total1.setText(String.valueOf(d));
}

if (type.getSelectedItem().equals("Compound")){
    for (int month=1;month<=m;month++){
       monthly2.append(String.valueOf(month+(". ")+d2+"\n"));
       total2.setText(String.valueOf(d2));
     } 
}

Simple interest works fine but compound monthly doesn't. I tried

amount:1000 rate:5 years 3.

And got

1. 5791.82
2. 5791.82
3. 5791.82

up to 60.

And I want it to show how much I have to pay monthly.

You only seem to calculate compound once, at the very beginning of your code. I'd create a method calculateCompoundInterest(int month) and then call this from within your loop like so:

for (int month=1; month <= m; month++) {
    String monthlyAmount = String.format("%.2f", calculateCompoundInterest(month));
    monthly2.append(String.valueOf(month+(". ")+monthlyAmount+"\n"));
    total2.setText(String.valueOf(d2));
} 

You are calculating monthly interest incorrectly.

formula a* Math.pow(1+r,y) needs to be applied like a* Math.pow(1+r/12,y*12) if compounded monthly. you need to convert your rate as well to use in the formula.

Please see this for more explanation of formula.

Here is the code to help you started:

for (int month=1;month<=m;month++){
   d2 = String.format("%.2f",a * Math.pow(1+ r/12, month));
   monthly2.append(String.valueOf(month+(". ")+d2+"\n"));
   total2.setText(String.valueOf(d2));
 }

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