Chapter 32: Financial Applets and Servlets 939
After declaring theresultvariable,actionperformed( )begins by obtaining the strings
from the three user-input text fields using the following sequence:
String amountStr = amountText.getText();
String periodStr = periodText.getText();
String rateStr = rateText.getText();
Next, it begins atryblock and then verifies that all three fields actually contain
information, as shown here:
try {
if(amountStr.length() != 0 &&
periodStr.length() != 0 &&
rateStr.length() != 0) {
Recall that the user must enter the original loan amount, the number of years for the
loan, and the interest rate. If all three text fields contain information, then the length of each
string will be greater than zero.
If the user has entered all the loan data, then the numeric values corresponding to those
strings are obtained and stored in the appropriate instance variable. Next,compute( )is
called to compute the loan payment, and the result is displayed in the read-only text field
referred to bypaymentText, as shown here:
principal = Double.parseDouble(amountStr);
numYears = Double.parseDouble(periodStr);
intRate = Double.parseDouble(rateStr) / 100;
result = compute();
paymentText.setText(nf.format(result));
Notice the call tonf.format(result). This causes the value inresultto be formatted as
previously specified (with two decimal digits) and the resulting string is returned. This
string is then used to set the text in theJTextFieldspecified bypaymentText.
If the user has entered a nonnumeric value into one of the text fields, then
Double.parseDouble( )will throw aNumberFormatException. If this happens, an error
message will be displayed on the status line and the Payment text field will be emptied, as
shown here:
showStatus(""); // erase any previous error message
} catch (NumberFormatException exc) {
showStatus("Invalid Data");
paymentText.setText("");
}
Otherwise, any previously reported error is removed.
The compute( ) Method
The calculation of the loan payment takes place incompute( ). It implements the formula
shown earlier and operates on the values inprincipal,intRate,numYears, andpayPerYear.
It returns the result.
NOTEOTE The basic skeleton used byRegPayis used by all the applets shown in this chapter.