Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 32: Financial Applets and Servlets 947


or pressed Compute. Display the result if all
fields are completed. */
public void actionPerformed(ActionEvent ae) {
double result = 0.0;

String targetStr = targetText.getText();
String periodStr = periodText.getText();
String rateStr = rateText.getText();
String compStr = compText.getText();

try {
if(targetStr.length() != 0 &&
periodStr.length() != 0 &&
rateStr.length() != 0 &&
compStr.length() != 0) {

targetValue = Double.parseDouble(targetStr);
numYears = Double.parseDouble(periodStr);
rateOfRet = Double.parseDouble(rateStr) / 100;
compPerYear = Integer.parseInt(compStr);

result = compute();

initialText.setText(nf.format(result));
}

showStatus(""); // erase any previous error message
} catch (NumberFormatException exc) {
showStatus("Invalid Data");
initialText.setText("");
}
}

// Compute the required initial investment.
double compute() {
double b, e;

b = (1 + rateOfRet/compPerYear);
e = compPerYear * numYears;

return targetValue / Math.pow(b, e);
}
}

Finding the Initial Investment Needed for a Desired Annuity


Another common financial calculation computes the amount of money that you must invest
so that a desired annuity, in terms of a regular withdrawal, can be paid. For example, you
might decide that you need $5,000 per month at retirement and that you will need that
amount for 20 years. The question is how much will you need to invest to secure that
annuity? The answer can be found using the following formula:

Initial Investment = ((regWD*wdPerYear) /rateOfRet) *
(1 – (1 / (rateOfRet/wdPerYear+ 1)wdPerYear*numYears))
Free download pdf