/* NPV Applet (a lite application to get started) */

import java.applet.*;
import java.awt.*;

public class NpvA extends Applet {
  TextField c0,c1,c2,c3,c4,c5,R;
  Label npvchar;
  public NpvA() {
    setLayout(new BorderLayout());
    add("North",new Label("Sample NPV Applet",Label.CENTER));
    Panel centr = new Panel();
      centr.setLayout(new FlowLayout());
      Panel leftcentr = new Panel();
        leftcentr.setLayout(new GridLayout(7,1));
        leftcentr.add(new Label("Cash Flows",Label.CENTER));
        Panel in0 = new Panel();
        in0.setLayout(new FlowLayout(FlowLayout.LEFT));
        in0.add(new Label("year 0"));
        in0.add(c0 = new TextField("-100",12));
        leftcentr.add(in0);
        Panel in1 = new Panel();
        in1.setLayout(new FlowLayout(FlowLayout.LEFT));
        in1.add(new Label("year 1"));
        in1.add(c1 = new TextField("5",12));
        leftcentr.add(in1);
        Panel in2 = new Panel();
        in2.setLayout(new FlowLayout(FlowLayout.LEFT));
        in2.add(new Label("year 2"));
        in2.add(c2 = new TextField("5",12));
        leftcentr.add(in2);
        Panel in3 = new Panel();
        in3.setLayout(new FlowLayout(FlowLayout.LEFT));
        in3.add(new Label("year 3"));
        in3.add(c3 = new TextField("5",12));
        leftcentr.add(in3);
        Panel in4 = new Panel();
        in4.setLayout(new FlowLayout(FlowLayout.LEFT));
        in4.add(new Label("year 4"));
        in4.add(c4 = new TextField("5",12));
        leftcentr.add(in4);
        Panel in5 = new Panel();
        in5.setLayout(new FlowLayout(FlowLayout.LEFT));
        in5.add(new Label("year 5"));
        in5.add(c5 = new TextField("105",12));
        leftcentr.add(in5);
        centr.add(leftcentr);
    Panel rightcentr = new Panel();
      rightcentr.setLayout(new GridLayout(4,1));
      rightcentr.add(new Label("Interest Rate (%):"));
      rightcentr.add(R = new TextField("5",12));
      rightcentr.add(new Label("The NPV is:"));
      rightcentr.add(npvchar = new Label("",Label.LEFT));
      npvchar.resize(180,npvchar.size().height);
      centr.add(rightcentr);
    add("Center",centr);
    recalc();}
  public boolean action(Event ev, Object arg) {
    if(ev.target instanceof TextField) {
      recalc();
      return true;}
    return false;}
  double text2double(TextField tf) {
    return Double.valueOf(tf.getText()).doubleValue();}
  public void recalc() {
    npvchar.setText(String.valueOf(npv(text2double(R)/100.0,
      text2double(c0),text2double(c1),text2double(c2),text2double(c3),
      text2double(c4),text2double(c5))));}
  float npv(double r, double c0, double c1, double c2, double c3,
    double c4, double c5) {
    double disc = 1.0/(1.0+r);
    return((float) (c0 + disc*(c1 + disc*(c2 + disc*(c3 + disc*(c4 + disc*c5))))));}}
