Java循环,需要代码简化的建议..

时间:2013-04-30 03:54:16

标签: java loops if-statement joptionpane

我只是作为初学者练习Java。所以这是一个问题: 假设您每月将100美元存入储蓄账户,年利率为5%。因此,每月利率为0.00417。在第一个月之后,帐户中的值变为100 *(1 + 0.00417)= 100.417,第二个月将是(100 + firstMonthValue)* 1.00417,然后每个月都这样继续。所以这是我的代码:

import javax.swing.JOptionPane;
public class vinalcialApplication {
    public static void main(String args[]){
        String monthlySaving = JOptionPane.showInputDialog("Enter the monthly savings");
        double monthsaving = Double.parseDouble(monthlySaving);
        //define monthly rate
        double monthlyrate = 1.00417;
        double totalrate = monthlyrate + 0.00417;
        double firstMonthValue = monthsaving * (totalrate);
    double secondMonthValue = (firstMonthValue + 100)*(monthlyrate);
    double thridMonthValue = (secondMonthValue + 100) * (monthlyrate);

     .........
    System.out.print("After the sixth month, the account value is " sixthMonthValue);
}

}

我的意思是代码可以工作,但是编写的代码太多了。我确信我可以使用循环或if语句来执行此操作,但还没有找到办法来做到这一点..你能帮忙吗? 谢谢。

3 个答案:

答案 0 :(得分:4)

如果我理解正确,这称为复利。

有一个数学公式可以实现你想要的而不需要循环。

以下是维基百科的公式

enter image description here

其中, A =未来价值,P =本金额(初始投资),r =年名义利率,利率,n =每年利息复利的次数,t =年数

希望这可以帮助您解决您想要的问题。我可以给你示例代码,但我认为将此公式转换为java语句相当容易。如果您需要更多信息,请告诉我们。

来源:http://en.wikipedia.org/wiki/Compound_interest

答案 1 :(得分:0)

数学可能是错误的,但基本概念是合理的。

public static void main(String[] args) {
    double monthsaving = 100;
    double monthlyrate = 1.00417;

    double savings = 0;
    // Loop for six months...
    for (int index = 0; index < 6; index++) {
        savings += monthsaving * monthlyrate;
        System.out.println(index + ":" + savings);
    }
    System.out.println(savings);
}

仔细查看Control Flow Statements,附上whiledo-whilefor语句

答案 2 :(得分:0)

import javax.swing.JOptionPane;
public class vinalcialApplication {
public static void main(String args[]){
    String monthlySaving = JOptionPane.showInputDialog("Enter the monthly savings");
    double monthsaving = Double.parseDouble(monthlySaving);
    //define monthly rate
    double monthlyrate = 1.00417;
    double totalrate = monthlyrate + 0.00417;
    double value = monthsaving * (totalrate);
    for(int i = 1; i<6;i++) {
        value = (value + 100)*(monthlyrate);
    }
    System.out.print("After the sixth month, the account value is " value);
}
相关问题