我的代码工作,我只是需要帮助,使其更短,更高效。我认为,一个for循环应该工作,但我不知道如何实现它。
public void onClick(View view) {
double loanAmount = Integer.parseInt(mLoanAmount.getText().toString());
double interestRate = Double.parseDouble(mInterestRate.getText().toString());
double rate = ((interestRate/100)/12);
double rate5 = Math.pow((1 + rate) , (-12*5));
double rate10 = Math.pow((1 + rate) , (-12*10));
double rate15 = Math.pow((1 + rate) , (-12*15));
double rate20 = Math.pow((1 + rate) , (-12*20));
double rate25 = Math.pow((1 + rate) , (-12*25));
double monthlyPayment5 = ((loanAmount * rate)/(1 - rate5));
double monthlyPayment10 = ((loanAmount * rate)/(1 - rate10));
double monthlyPayment15 = ((loanAmount * rate)/(1 - rate15));
double monthlyPayment20 = ((loanAmount * rate)/(1 - rate20));
double monthlyPayment25 = ((loanAmount * rate)/(1 - rate25));
mMonthly5.setText(new DecimalFormat("##.##").format(monthlyPayment5));
mMonthly10.setText(new DecimalFormat("##.##").format(monthlyPayment10));
mMonthly15.setText(new DecimalFormat("##.##").format(monthlyPayment15));
mMonthly20.setText(new DecimalFormat("##.##").format(monthlyPayment20));
mMonthly25.setText(new DecimalFormat("##.##").format(monthlyPayment25));
}
如果你发现我的代码是非常重复,唯一改变的事情就是在变量名称中的数字。
你的代码可以改写成
public void onClick(View view) {
double loanAmount = Integer.parseInt(mLoanAmount.getText().toString());
double interestRate = Double.parseDouble(mInterestRate.getText().toString());
double baseRate = ((interestRate/100)/12);
double rates[] = {-12*5, -12*10, -12*15, -12*20, -12*25};
TextView views = {mMonthly5, mMonthly10, mMonthly15, mMonthly20, mMonthly25};
for(int i=0; i<rates.length; i++) {
double actualRate = Math.pow((1 + baseRate) , rates[i]);
double monthlyPayment = ((loanAmount * baseRate)/(1 - actualRate));
views[i].setText(new DecimalFormat("##.##").format(monthlyPayment));
}
}
我希望这个例子对你有所帮助的未来。