Chapter 32: Financial Applets and Servlets 943
nf.setMaximumFractionDigits(2);
}
/* User pressed Enter on a text field or
pressed Compute. Display the result if all
fields are completed. */
public void actionPerformed(ActionEvent ae) {
double result = 0.0;
String amountStr = amountText.getText();
String periodStr = periodText.getText();
String rateStr = rateText.getText();
String compStr = compText.getText();
try {
if(amountStr.length() != 0 &&
periodStr.length() != 0 &&
rateStr.length() != 0 &&
compStr.length() != 0) {
principal = Double.parseDouble(amountStr);
numYears = Double.parseDouble(periodStr);
rateOfRet = Double.parseDouble(rateStr) / 100;
compPerYear = Integer.parseInt(compStr);
result = compute();
futvalText.setText(nf.format(result));
}
showStatus(""); // erase any previous error message
} catch (NumberFormatException exc) {
showStatus("Invalid Data");
futvalText.setText("");
}
}
// Compute the future value.
double compute() {
double b, e;
b = (1 + rateOfRet/compPerYear);
e = compPerYear * numYears;
return principal * Math.pow(b, e);
}
}
Finding the Initial Investment Required to Achieve a Future Value
Sometimes you will want to know how large an initial investment is required to achieve
some future value. For example, if you are saving for your child’s college education and
you know that you will need $75,000 in five years, how much money do you need to invest
at 7 percent to reach that goal? TheInitInvapplet developed here can answer that question.