/*
    This program modifies the example from pages 215-216
    of "Java for Students". A field is added for entering
    the number of compounding periods used during a year.
*/
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Accumulate2 extends Applet implements ActionListener {

    private Button year;
    private TextField interestField, amountField, compoundField;

    private Invest myMoney;  //create a variable of type Invest

    public void init() {
        Label amountLabel = new Label("Enter amount:");
        add(amountLabel);

        amountField = new TextField(8);
        add(amountField);
        amountField.addActionListener(this);

        Label rateLabel = new Label("Enter interest rate");
        add(rateLabel);

        interestField = new TextField(4);
        add(interestField);
        interestField.addActionListener(this);

        Label compoundLabel = new Label("Enter number of compoundings");
        add(compoundLabel);

        compoundField = new TextField(4);
        add(compoundField);
        compoundField.addActionListener(this);

        year = new Button("Another Year");
        add(year);
        year.addActionListener(this);

        myMoney = new Invest();   //create an object of type Invest
                                  //and call it myMoney
    }

    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == amountField) {
            float amount = Integer.parseInt(amountField.getText());
            myMoney.setAmount(amount);
        }
        if (event.getSource() == interestField) {
            float rate = Float.valueOf(interestField.getText()).floatValue();
            myMoney.setRate(rate);
        }
        if (event.getSource() == compoundField) {
            int n = Integer.parseInt(compoundField.getText());
            myMoney.setCompounding(n);
        }
        if (event.getSource() == year)
            myMoney.anotherYear();
        repaint();
    }

    public void paint (Graphics g) {
        myMoney.displayInterest(g);
    }
}


class Invest {
    private float interestRate;
    private float amount;
    private int dollars, cents;
    private int compounding;

    public void setAmount(float amount) {
        this.amount = amount;
    }

    public void setRate(float rate) {
        interestRate = rate;
    }

    public void setCompounding(int n) {
        compounding = n;
    }

    public void anotherYear() {
        amount = (float)Math.pow(1+interestRate/100.0/compounding, compounding)*amount;
        dollars = (int)amount;
        cents = Math.round(100.0f * (amount - dollars));
    }

    public void displayInterest(Graphics g) {
        g.drawString("Your money at the end of the year is", 10, 150);
        g.drawString(dollars + " dollars " + cents + " cents", 10, 170);
    }
}
