932 Part IV: Applying Java
Finding the Payments for a Loan
Perhaps the most popular financial calculation is the one that computes the regular payments
on a loan, such as a car or house loan. The payments on a loan are found by using the
following formula:
Payment = (intRate* (principal/payPerYear)) /
(1 – ((intRate/payPerYear) + 1)–payPerYear*numYears)
whereintRatespecifies the interest rate,principalcontains the starting balance,payPerYear
specifies the number of payments per year, andnumYearsspecifies the length of the loan
in years.
The following applet calledRegPayuses the preceding formula to compute the
payments on a loan given the information entered by the user. Like all of the applets in
this chapter,RegPayis a Swing-based applet. This means that it extends theJAppletclass
and uses the Swing classes to provide the user interface. Notice that it also implements the
ActionListenerinterface.
// A simple loan calculator applet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
/*
<applet code="RegPay" width=320 height=200>
</applet>
*/
public class RegPay extends JApplet
implements ActionListener {
JTextField amount Text, paymentText, periodText, rateText;
JButton doIt;
double principal; // original principal
double intRate; // interest rate
double numYears; // length of loan in years
/* Number of payments per year. You could
allow this value to be set by the user. */
final int payPerYear = 12;
NumberFormat nf;
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);