我的代码有效,我只需要帮助使其更短,更有效。我认为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));
}
如果您发现我的代码非常重复,那么唯一改变的就是变量名称中的数字。
答案 0 :(得分:0)
您的代码可以重写为
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));
}
}
我希望这个示例将来对您有所帮助。