【问题标题】:Need help making my code shorter!! (Noob here)需要帮助缩短我的代码!! (这里是菜鸟)
【发布时间】:2019-02-03 18:31:21
【问题描述】:

我的代码有效,我只需要帮助使其更短、更高效。我认为 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));
}

如果你注意到我的代码非常重复,唯一改变的是变量名中的数字。

【问题讨论】:

  • 请复制并粘贴您的代码而不是图像。使用方法,并传入你需要的东西来得到你想要的东西。
  • 嗨,Raulyn,实际上您通常可以要求您的 ide 为您执行此操作。 Intellij 非常擅长重组和优化事物。所以我建议你用谷歌搜索你正在使用的任何 ide +“如何重新格式化/优化”+ ide 的名称。但是,如果您真的想要直接反馈如何缩短/改进您的代码,我建议您粘贴实际代码。尽管请记住,stackoverflow 上的人可能非常苛刻。 (见上面的评论)
  • 我是 Stackoverflow 的新手。我尝试显示代码,但它一直说格式不正确。

标签: java android for-loop


【解决方案1】:

您的代码可以重写为

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));
    }
}

希望这个例子对你以后有所帮助。

【讨论】:

  • 你成功了。 mMonthly5 是一个 TextView 类型。我必须修复的唯一另一件事是monthlyPayntent5,它必须只是monthlyPayntent(在最后一行)。谢谢你。我真的很感激。
  • 糟糕,抱歉 :) 代码已修复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多