Search code examples
javaloopsif-statementjoptionpane

Java loop, need suggestion for code simplification..


I am just practicing Java as a beginner. So here is the question: Suppose you save $100 each month into a savings account with the annual interest rate 5%. Thus, the monthly interest rate is 0.00417. After the first month, the value in the account becomes 100 * (1 + 0.00417) = 100.417 and the second month will be (100 + firstMonthValue) * 1.00417, and then goes on like so every month. So here is my code:

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

}

I mean the code works but it is too much code to write.. I am sure I can use a loop or if statement to do this but haven't figured a way to do it yet.. can you please help? Thank you.


Solution

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