Link to home
Start Free TrialLog in
Avatar of DeeDee2309
DeeDee2309

asked on

Mortgage Applet Program using an array??

At the bottom, I have included my current program.  I would like to modify the program using an array for mortgage options.  The options are,  7 year at 5.35%, 15 year at 5.5 %, and 30 year at 5.75%.  I need to use a loop to show the loan balance, interest paid and each payment for the first 12 months of the loan, and  exception handling so that an appropriate error message is printed if an illegal mortgage amount is entered.  I must also allow the user to loop back and enter a new amount and make a new selection, or quit.

Here's my program:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

class AppletMortgage  //name of applet program
{
   public static void main(String args[])
   {
      Frame f = new NewFrame();
      f.show();
   }
} // java class



class NewFrame extends Frame implements TextListener {

   TextField principalField = new TextField("", 10),
             interestRateField = new TextField("", 10),
             yearsField = new TextField("", 10),
             paymentAmtField = new TextField("", 10);
   double principal;
   double interestRate;
   double fractionRate;
   int years;
   final int paymentsPerYear = 12;
   double monthlyRate;
   double paymentAmt;
   double months;
   
   public NewFrame()
   {
      setTitle(" Mortgage Calculator");
       
           
      Label principalLabel = new Label("Amount of Loan $"),
            interestRateLabel = new Label("Interest Rate"),
            yearsLabel = new Label("Number of Years"),
            paymentAmtLabel = new Label("Monthly Payment $");
            JButton quitButton= new JButton ("Quit");
            quitButton.addActionListener (new quit());
           
           
      Panel principalFieldPanel = new Panel(new GridLayout(5,2));

      principalFieldPanel.add(principalLabel);
      principalFieldPanel.add(principalField);
      principalFieldPanel.add(interestRateLabel);
      principalFieldPanel.add(interestRateField);
      principalFieldPanel.add(yearsLabel);
      principalFieldPanel.add(yearsField);
      principalFieldPanel.add(paymentAmtLabel);
      principalFieldPanel.add(paymentAmtField);
      principalFieldPanel.add(quitButton);
      add(principalFieldPanel);


      principalField.addTextListener(this);
      interestRateField.addTextListener(this);
      yearsField.addTextListener(this);
      addWindowListener(new MyAdapter(this));

      pack();
      show();

   } //end NewFrame class

   DecimalFormat currency = new DecimalFormat("####0.00"); // to convert into decimal

   public void textValueChanged (TextEvent e)
   {
      Object source=e.getSource();
      if (source == principalField ||
          source == interestRateField ||
          source == yearsField)
      {
         try
         {
            principal = Double.parseDouble(principalField.getText());
            fractionRate = Double.parseDouble(interestRateField.getText());
            interestRate = fractionRate/100.0;
            years = Integer.parseInt(yearsField.getText());
                  monthlyRate = interestRate/paymentsPerYear;
                  
           
            months = years * paymentsPerYear;
            paymentAmt = principal*monthlyRate / (1 - (Math.pow(1/(1 + monthlyRate), months)));// for monthly payment amount

            paymentAmtField.setText(currency.format(paymentAmt));
         } //end monthly mortgage payment
         catch (NumberFormatException ex) {}
      }
   } // used to change values
}//ends TextListener

class quit implements ActionListener{
      public void actionPerformed (ActionEvent e){
            System.exit(0);
      } //used for the quit button
}      //end class



 

   
ASKER CERTIFIED SOLUTION
Avatar of nesnemis
nesnemis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DeeDee2309
DeeDee2309

ASKER

That truly is excellent.  I like that you can click on the years, to display 7, 15, or 30. How can can I have an interest rate choice as well, so if you click interest rate, you have a choice of 7, 15 or 30 years, the same way as when you click on years to have a choice?    I also have to add a text box that will display the following:

double balance = principal;
double newMonthlyRate;
double newBalance;
int paymentNum=1;


msgArea = new TextArea("", 15, 60);// I am not sure if I named this right
        msgArea.setEditable(false);
       
StringBuffer msg = new StringBuffer(); //not sure if this is right either
            msg.append(" " + paymentNum + "\t$ " + currency.format(paymentAmt)+"\t\t"  + currency.format(newMonthlyRate) + "\t\t " + currency.format(principal) + " \t " + currency.format(newBalance ));
           

msg.append(" " + paymentNum + "\t$ " + currency.format(paymentAmt)+"\t\t"  + currency.format(newMonthlyRate) + "\t\t " + currency.format(principal) + " \t " + currency.format(newBalance ));
           
  //then a running total as in,
  for (int lineNumb=1;paymentNum<=12 ;lineNumb++)
{
      principal = paymentAmt-newMonthlyRate;
      newMonthlyRate = balance*monthlyRate;
                newBalance = balance-principal;
      balance = newBalance;
   
  paymentNum++;
 }


// I just can't get these placed right without messing everything up.  Please help.  I am still a beginner at programming and get very confused.
if you want both of them to be JComboBox, it's even easier:

change the textfield to JComboBox, then change the addTextListener to addActionListener, in actionPerformed use:
if(e.getSource() == yearsCombo)
      interestRateCombo.setSelectedIndex(yearsCombo.getSelectedIndex());
else if(e.getSource() == interestRateCombo)
      yearsCombo.setSelectedIndex(interestRateCombo.getSelectedIndex());

You must also add items to interestRateCombo in the same way as for yearsCombo:

Enumeration e = interests.elements();
      while(e.hasMoreElements())
      {
            InterestRate ir = (InterestRate) e.nextElement();
            yearsCombo.addItem(ir.years+"");
            interestRateCombo.addItem(ir.interestRate+"");
      }

The complete code:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Vector;

class AppletMortgage  //name of applet program
{
   public static void main(String args[])
   {
      Frame f = new NewFrame();
      f.show();
   }
} // java class



class NewFrame extends Frame implements TextListener, ActionListener {

   TextField principalField = new TextField("", 10),
             paymentAmtField = new TextField("", 10);
   JComboBox yearsCombo = new JComboBox(), interestRateCombo = new JComboBox();
   double principal;
   double interestRate;
   double fractionRate;
   int years;
   final int paymentsPerYear = 12;
   double monthlyRate;
   double paymentAmt;
   double months;
   
   Vector interests;
   
   public NewFrame()
   {
      setTitle(" Mortgage Calculator");
     
      interests = new Vector();
      interests.addElement(new InterestRate(7, 5.35));
      interests.addElement(new InterestRate(15, 5.5));
      interests.addElement(new InterestRate(30, 5.75));
     
      Enumeration e = interests.elements();
      while(e.hasMoreElements())
      {
            InterestRate ir = (InterestRate) e.nextElement();
            yearsCombo.addItem(ir.years+"");
            interestRateCombo.addItem(ir.interestRate+"");
      }
     
      Label principalLabel = new Label("Amount of Loan $"),
            interestRateLabel = new Label("Interest Rate"),
            yearsLabel = new Label("Number of Years"),
            paymentAmtLabel = new Label("Monthly Payment $");
            JButton quitButton= new JButton ("Quit");
            quitButton.addActionListener (new quit());
           
           
      Panel principalFieldPanel = new Panel(new GridLayout(5,2));

      principalFieldPanel.add(principalLabel);
      principalFieldPanel.add(principalField);
      principalFieldPanel.add(interestRateLabel);
      principalFieldPanel.add(interestRateCombo);
      principalFieldPanel.add(yearsLabel);
      principalFieldPanel.add(yearsCombo);
      principalFieldPanel.add(paymentAmtLabel);
      principalFieldPanel.add(paymentAmtField);
      principalFieldPanel.add(quitButton);
      add(principalFieldPanel);


      principalField.addTextListener(this);
      interestRateCombo.addActionListener(this);
      yearsCombo.addActionListener(this);

      pack();
      show();

   } //end NewFrame class

   DecimalFormat currency = new DecimalFormat("####0.00"); // to convert into decimal
    public void actionPerformed (ActionEvent e){
          if(e.getSource() == yearsCombo)
                interestRateCombo.setSelectedIndex(yearsCombo.getSelectedIndex());
            else if(e.getSource() == interestRateCombo)
                  yearsCombo.setSelectedIndex(interestRateCombo.getSelectedIndex());
     }
   public void textValueChanged (TextEvent e)
   {
      Object source=e.getSource();
      if (source == principalField)
      {
         try
         {
            principal = Double.parseDouble(principalField.getText());
            fractionRate = Double.parseDouble(interestRateCombo.getSelectedItem().toString());
            interestRate = fractionRate/100.0;
            years = Integer.parseInt(yearsCombo.getSelectedItem().toString());
               monthlyRate = interestRate/paymentsPerYear;
               
           
            months = years * paymentsPerYear;
            paymentAmt = principal*monthlyRate / (1 - (Math.pow(1/(1 + monthlyRate), months)));// for monthly payment amount

            paymentAmtField.setText(currency.format(paymentAmt));
         } //end monthly mortgage payment
         catch (NumberFormatException ex) {}
      }
   } // used to change values
}//ends TextListener

class quit implements ActionListener{
     public void actionPerformed (ActionEvent e){
          System.exit(0);
     } //used for the quit button
}     //end class
class InterestRate
{
      int years;
      double interestRate;
      public InterestRate(int y, double i)
      {
            years = y;
            interestRate = i;
      }
}
when you add a component that is much wider than the rest you have to put them in different panels. Else it will look bad. I've added the inputfields to an own panel and used BorderLayout for the main panel. this way you can avoid the problem.

The code...

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Vector;

class AppletMortgage  //name of applet program
{
   public static void main(String args[])
   {
      Frame f = new NewFrame();
      f.show();
   }
} // java class



class NewFrame extends Frame implements TextListener, ActionListener {

   TextField principalField = new TextField("", 10),
             paymentAmtField = new TextField("", 10);
   JComboBox yearsCombo = new JComboBox(), interestRateCombo = new JComboBox();
   JTextArea msgArea;
   double principal;
   double interestRate;
   double fractionRate;
   int years;
   final int paymentsPerYear = 12;
   double monthlyRate;
   double paymentAmt;
   double months;
   
   Vector interests;
   
   public NewFrame()
   {
      setTitle(" Mortgage Calculator");
     
      interests = new Vector();
      interests.addElement(new InterestRate(7, 5.35));
      interests.addElement(new InterestRate(15, 5.5));
      interests.addElement(new InterestRate(30, 5.75));
     
      Enumeration e = interests.elements();
      while(e.hasMoreElements())
      {
            InterestRate ir = (InterestRate) e.nextElement();
            yearsCombo.addItem(ir.years+"");
            interestRateCombo.addItem(ir.interestRate+"");
      }
     
      Label principalLabel = new Label("Amount of Loan $"),
            interestRateLabel = new Label("Interest Rate"),
            yearsLabel = new Label("Number of Years"),
            paymentAmtLabel = new Label("Monthly Payment $");
            JButton quitButton= new JButton ("Quit");
            quitButton.addActionListener (new quit());
   
    msgArea = new JTextArea(15, 60);
   msgArea.setEditable(false);
      JScrollPane scrArea = new JScrollPane(msgArea);      // in case you need it...
      
      yearsCombo.setBackground(Color.WHITE);
      interestRateCombo.setBackground(Color.WHITE);
              
           
      JPanel principalFieldPanel = new JPanel(new GridLayout(4,2));
     
     
      JPanel mainPanel = new JPanel(new BorderLayout());

      principalFieldPanel.add(principalLabel);
      principalFieldPanel.add(principalField);
      principalFieldPanel.add(interestRateLabel);
      principalFieldPanel.add(interestRateCombo);
      principalFieldPanel.add(yearsLabel);
      principalFieldPanel.add(yearsCombo);
      principalFieldPanel.add(paymentAmtLabel);
      principalFieldPanel.add(paymentAmtField);
      
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(principalFieldPanel, BorderLayout.WEST);
     
      mainPanel.add(topPanel, BorderLayout.NORTH);
      mainPanel.add(scrArea, BorderLayout.CENTER);
      mainPanel.add(quitButton, BorderLayout.SOUTH);
      
      add(mainPanel);
      
      principalField.addTextListener(this);
      interestRateCombo.addActionListener(this);
      yearsCombo.addActionListener(this);
     
      pack();
      show();

   } //end NewFrame class
      
      private String msgText()
      {
            double balance = principal;
            double newMonthlyRate = 0.0;
            double newBalance = 0.0;
            int paymentNum=1;

            
            StringBuffer msg = new StringBuffer(); //not sure if this is right either
            msg.append(" " + paymentNum + "\t$ " + currency.format(paymentAmt)+"\t\t"  + currency.format(newMonthlyRate) + "\t\t " + currency.format(principal) + " \t " + currency.format(newBalance ));
                  
      
            msg.append(" " + paymentNum + "\t$ " + currency.format(paymentAmt)+"\t\t"  + currency.format(newMonthlyRate) + "\t\t " + currency.format(principal) + " \t " + currency.format(newBalance ));
                  
            //then a running total as in,
            for (int lineNumb=1;paymentNum<=12 ;lineNumb++)
            {
                  principal = paymentAmt-newMonthlyRate;
                  newMonthlyRate = balance*monthlyRate;
                  newBalance = balance-principal;
                  balance = newBalance;
          
                  paymentNum++;
            }
            
            
            return msg.toString();
      }

   DecimalFormat currency = new DecimalFormat("####0.00"); // to convert into decimal
    public void actionPerformed (ActionEvent e){
          if(e.getSource() == yearsCombo)
                interestRateCombo.setSelectedIndex(yearsCombo.getSelectedIndex());
            else if(e.getSource() == interestRateCombo)
                  yearsCombo.setSelectedIndex(interestRateCombo.getSelectedIndex());
            msgArea.setText(msgText());
     }
   public void textValueChanged (TextEvent e)
   {
      Object source=e.getSource();
      if (source == principalField)
      {
         try
         {
            principal = Double.parseDouble(principalField.getText());
            fractionRate = Double.parseDouble(interestRateCombo.getSelectedItem().toString());
            interestRate = fractionRate/100.0;
            years = Integer.parseInt(yearsCombo.getSelectedItem().toString());
               monthlyRate = interestRate/paymentsPerYear;
               
           
            months = years * paymentsPerYear;
            paymentAmt = principal*monthlyRate / (1 - (Math.pow(1/(1 + monthlyRate), months)));// for monthly payment amount

            paymentAmtField.setText(currency.format(paymentAmt));
         } //end monthly mortgage payment
         catch (NumberFormatException ex) {}
         msgArea.setText(msgText());
      }
   } // used to change values
}//ends TextListener

class quit implements ActionListener{
     public void actionPerformed (ActionEvent e){
          System.exit(0);
     } //used for the quit button
}     //end class
class InterestRate
{
      int years;
      double interestRate;
      public InterestRate(int y, double i)
      {
            years = y;
            interestRate = i;
      }
}
Thanks, again, that is excellent work.  I did make a few changes to the lay out and also in the message area, I couldn't read the heading for the payment number, payment amount, principal, interest and new balance.  I can't seem to get the info to scroll under that heading, it scrolls all to the right.  How do I get it under the heading?  

the code:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Vector;

class AppletMortgage3  //name of applet program
{
   public static void main(String args[])
   {
      Frame f = new NewFrame();
      f.show();
   }
} // java class

class NewFrame extends Frame implements TextListener, ActionListener {

   TextField principalField = new TextField("", 10),
             paymentAmtField = new TextField("", 10);
   JComboBox yearsCombo = new JComboBox(), interestRateCombo = new JComboBox();
   JTextArea msgArea;
   double principal;
   double interestRate;
   double fractionRate;
   int years;
   final int paymentsPerYear = 12;
   double monthlyRate;
   double paymentAmt;
   double months;
   
   Vector interests;
   
   public NewFrame()
   {
      setTitle(" Mortgage Calculator");
     
      interests = new Vector();
      interests.addElement(new InterestRate(7, 5.35));
      interests.addElement(new InterestRate(15, 5.5));
      interests.addElement(new InterestRate(30, 5.75));
     
      Enumeration e = interests.elements();
      while(e.hasMoreElements())
      {
           InterestRate ir = (InterestRate) e.nextElement();
           yearsCombo.addItem(ir.years+"");
           interestRateCombo.addItem(ir.interestRate+"");
      }
     
      Label
      yearsLabel = new Label("Number of Years"),
       interestRateLabel = new Label("Interest Rate"),
       principalLabel = new Label("Amount of Loan $"),
     
            paymentAmtLabel = new Label("Monthly Payment $");
            JButton quitButton= new JButton ("Quit");
            quitButton.addActionListener (new quit());
           
    msgArea = new JTextArea("", 15, 45);
   msgArea.setEditable(false);
   
     JScrollPane scrArea = new JScrollPane(msgArea);     // in case you need it...
     
     yearsCombo.setBackground(Color.WHITE);
     interestRateCombo.setBackground(Color.WHITE);
             
           
      JPanel principalFieldPanel = new JPanel(new GridLayout(4,2));
     
     
      JPanel mainPanel = new JPanel(new BorderLayout());
      principalFieldPanel.add(yearsLabel);
     principalFieldPanel.add(yearsCombo);
     principalFieldPanel.add(interestRateLabel);
     principalFieldPanel.add(interestRateCombo);
     principalFieldPanel.add(principalLabel);
     principalFieldPanel.add(principalField);
         
     principalFieldPanel.add(paymentAmtLabel);
     principalFieldPanel.add(paymentAmtField);
     
     JPanel topPanel = new JPanel(new BorderLayout());
     topPanel.add(principalFieldPanel, BorderLayout.WEST);
     
     mainPanel.add(topPanel, BorderLayout.NORTH);
     mainPanel.add(scrArea, BorderLayout.CENTER);
     mainPanel.add(quitButton, BorderLayout.SOUTH);
     
     add(mainPanel);
      yearsCombo.addActionListener(this);
       interestRateCombo.addActionListener(this);
      principalField.addTextListener(this);
                 
      pack();
      show();

   } //end NewFrame class
     
     private String msgText()
     {
          StringBuffer msg = new StringBuffer();
            msg.append( "Number \t" + "Payment\t" +  " Interest\t" + "Principal\t" + "Ending Balance");    
          
            double balance = principal;
          double newMonthlyRate = 0.0;
          double newBalance = 0.0;
          int paymentNum=1;
                   
          for (int lineNumb=1;paymentNum<=12 ;lineNumb++)
          {
               principal = paymentAmt-newMonthlyRate;
               newMonthlyRate = balance*monthlyRate;
               newBalance = balance-principal;
               balance = newBalance;
             
                msg.append(" "+ paymentNum + "\t$ " + currency.format(paymentAmt)+"\t\t"  + currency.format(newMonthlyRate) + "\t\t " + currency.format(principal) + " \t " + currency.format(newBalance ));
         
               paymentNum++;
          }
         
         
          return msg.toString();
     }

   DecimalFormat currency = new DecimalFormat(",000.00"); // to convert into decimal
    public void actionPerformed (ActionEvent e){
         if(e.getSource() == yearsCombo)
              interestRateCombo.setSelectedIndex(yearsCombo.getSelectedIndex());
          else if(e.getSource() == interestRateCombo)
               yearsCombo.setSelectedIndex(interestRateCombo.getSelectedIndex());
          msgArea.setText(msgText());
     }
   public void textValueChanged (TextEvent e)
   {
      Object source=e.getSource();
      if (source == principalField)
      {
         try
         {
            principal = Double.parseDouble(principalField.getText());
            fractionRate = Double.parseDouble(interestRateCombo.getSelectedItem().toString());
            interestRate = fractionRate/100.0;
            years = Integer.parseInt(yearsCombo.getSelectedItem().toString());
               monthlyRate = interestRate/paymentsPerYear;
               
           
            months = years * paymentsPerYear;
            paymentAmt = principal*monthlyRate / (1 - (Math.pow(1/(1 + monthlyRate), months)));// for monthly payment amount

            paymentAmtField.setText(currency.format(paymentAmt));
         } //end monthly mortgage payment
         catch (NumberFormatException ex) {}
         msgArea.setText(msgText());
      }
   } // used to change values
}//ends TextListener

class quit implements ActionListener{
     public void actionPerformed (ActionEvent e){
          System.exit(0);
     } //used for the quit button
}     //end class
class InterestRate
{
     int years;
     double interestRate;
     public InterestRate(int y, double i)
     {
          years = y;
          interestRate = i;
     }
}
You have to add the components you want scroll with to a JScrollPane.

I can't make the whole program for you, I must say that I have answered your original question...