Question

Java Programming----- Creating a Mortgage Calculator Program

Write the program in Java (with a graphical user interface) and have it calculate and display the mortgage payment amount from user input of the amount of the mortgageand the user's selection from a menu of available mortgage loans:
•7 years at 5.35%
•15 years at 5.5%
•30 years at 5.75%
Use an array for the mortgage data for the different loans. Read the interest rates to fill the array from a sequential file. Display the mortgage payment amountfollowed by the loan balance and interest paid for each payment over the term of the loan. Add graphics in the form of a chart. Allow the user to loop back and enter anew amount and make a new selection or quit. Please insert comments in the program to document the program.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

you need like this behind it

We will let L = loan, n = number of months for repayment, starting at
end of first month, r = percentage interest rate per year, (take r/12
as monthly rate). P = amount of repayment per month (starting at end
of first month).

If we consider the loan first, this would increase by a factor
(1 + r/1200) per month, so after n months the value of the loan would
have increased to L(1 + r/1200)^n

Now consider the repayments. These are $P per month, but the value of
the earlier repayments also increases at a compound rate (1 + r/1200).
Thus after the second repayment, the value of the repayments is:

P + P(1 + r/1200) and after three months it would be:
P + P(1 + r/1200) + P(1 + r/1200)^2 and after n months it would be:
P{1 + (1+r/1200) + (1+r/1200)^2 + ..... + (1+r/1200)^(n-1)}

This is a geometric series with n terms, first term = 1 and common
ratio (1+r/1200), so the sum of n terms is given by

P{(1+r/1200)^n - 1}/{(1+r/1200)-1)}
= P{(1+r/1200)^n - 1}/(r/1200)
= 1200P{(1+r/1200)^n - 1}/r

We must now equate the total repayments to total value of the loan,
and this gives:

1200P{(1+r/1200)^n - 1}/r = L(1+r/1200)^n

P = Lr(1+r/1200)^n/[1200{(1+r/1200)^n - 1}]

Example. Find the monthly repayments on a loan of $20,000 over 15
years at 12 percent per year compound interest.

Here we have n = 12*15 = 180 months, r = 12, and L = 20000.
We want to find P.

1+r/1200 = 1 + 12/1200 = 1.01 and the above formula becomes


P = {20000*12*1.01^180}/{1200*(1.01^180 - 1)}

= {20000*12*5.99}/{1200*(5.99 - 1)}

= 1437600/5988

= $240.08
answered by: MUDASIR
Add a comment
Answer #2
//these packages need to be imported
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.text.DecimalFormat;
//this is the calculator class
public class Calculator extends JPanel implements ActionListener
{

protected JComboBox MortCombo;
protected JLabel lblprincipal, lblinterestRate, lblTerm, lblmonthlyPayment;
protected JButton calculate, Clear;
protected JTextField principal, interestRate, Term, monthlyPayment;
protected TextArea MortTextField;
public Calculator()
{

String [] termString = {"7", "15", "30"};
String [] rateString = {"0.535", "0.055", "0.0575"};
//creates labels and fields
lblprincipal=new JLabel("Principal Amount:");
principal = new JTextField("",10);
lblinterestRate=new JLabel("Interest Rate:");
interestRate = new JTextField("",10);
lblTerm=new JLabel("Term:");
Term = new JTextField("",10);
lblmonthlyPayment=new JLabel("Monthly Payment:");
monthlyPayment = new JTextField("",10);
MortCombo=new JComboBox(comboItems);
MortTextField=new TextArea(10,120);
//The buttons are created here
calculate = new JButton("Calculate");
calculate.setActionCommand("GO");
Clear = new JButton("Clear");
Clear.setActionCommand("Clear");
//Added action for buttons here
calculate.addActionListener(this);
Clear.addActionListener(this);
add(lblprincipal);
add(principal);
add(lblinterestRate);
add(MortCombo);
add(lblTerm);
add(Term);
add(lblmonthlyPayment);
add(monthlyPayment);
add(calculate);
add(Clear);
add(MortTextField);
}
public void actionPerformed(ActionEvent e)
{

if ("GO".equals(e.getActionCommand()))
{

CalculateMortgage();
}
else
{

principal.setText("");
interestRate.setText("");
Term.setText("");
monthlyPayment.setText("");
}
}

//This is where the interest rate reads and shows it in the principal field
public void CalculateMortgage()
{

double dblprincipal=Double.parseDouble(principal.getText());
double dblinterestRate=Double.parseDouble((String)MortCombo.getSelectedItem());
int intTerm=Integer.parseInt(Term.getText());
DecimalFormat money = new DecimalFormat("$0.00");
double MonthlyPayment=0.0;
double InterestPayment=0.0;
double PrincipalBal=0.0;
double MIntRate=dblinterestRate/1200;
int MTerms=intTerm * 12;
//The formula for monthly payment here
MonthlyPayment=(dblprincipal * MIntRate) / (1-Math.pow((MIntRate+1),-MTerms));
//This is where monthly payments gets converted to decimal format
monthlyPayment.setText("" + (money.format(MonthlyPayment)));
MortTextField.append("Month No.ttMonthly PaymenttttLoan BalancetttInterest Paymentn");
MortTextField.append("1ttt" + MonthlyPayment + PrincipalBal + InterestPayment + "n");

for (int counter=1; counter < MTerms; counter++)
{

MortTextField.append((counter + 1) + "ttt" + MonthlyPayment + PrincipalBal + InterestPayment + "n");
}
}

private static void createAndShowGui()
{
//Jframe here
JFrame frame = new JFrame("Mortgage Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calculator myCalculator = new Calculator();
myCalculator.setOpaque(true);
frame.setContentPane(myCalculator);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args)
{

javax.swing.SwingUtilities.invokeLater(
new Runnable()
{

public void run()
{
createAndShowGui();
}
}
);
}
answered by: concy
Add a comment
Answer #3
import java.awt.*; //to create buttons, etc w/o actions
import java.awt.event.*; //to create an event or action
import javax.swing.*;
import javax.swing.JButton; //to create a button
import javax.swing.JTextField; //to create a text field
import java.text.DecimalFormat; //to import decimal format for money

//Class
public class MortgageText extends JPanel implements ActionListener
{
//Global Variable
protected JComboBox MortCombo;
protected JLabel lblprincipal, lblinterestRate, lblTerm, lblmonthlyPayment;
protected JButton calculate, Clear;
protected JTextField principal, interestRate, Term, monthlyPayment;
protected TextArea MortTextField;

public MortgageText()
{
String[] comboItems={"5.35","5.50","5.75","10.0"};

//creates labels and fields
lblprincipal=new JLabel("Principal Amount:");
principal = new JTextField("",10);
lblinterestRate=new JLabel("Interest Rate:");
interestRate = new JTextField("",10);
lblTerm=new JLabel("Term:");
Term = new JTextField("",10);
lblmonthlyPayment=new JLabel("Monthly Payment:");
monthlyPayment = new JTextField("",10);
MortCombo=new JComboBox(comboItems);
MortTextField=new TextArea(10,120);

//create buttons
calculate = new JButton("Calculate"); //button used to calculate mortgage payment
calculate.setActionCommand("GO");

Clear = new JButton("Clear"); //button used to clear data from the fields
Clear.setActionCommand("Clear");


//add action to button
calculate.addActionListener(this);
Clear.addActionListener(this);

add(lblprincipal);
add(principal);
add(lblinterestRate);
add(MortCombo);
add(lblTerm);
add(Term);
add(lblmonthlyPayment);
add(monthlyPayment);
add(calculate);
add(Clear);
add(MortTextField);

}
public void actionPerformed(ActionEvent e)
{
if ("GO".equals(e.getActionCommand()))
{
CalculateMortgage();
}
else
{
principal.setText("");
interestRate.setText("");
Term.setText("");
monthlyPayment.setText("");
}
}

// principal.setText(interestRate.getText()); --this will read the interestRate text field and copy it to the principal field

public void CalculateMortgage()
{
double dblprincipal=Double.parseDouble(principal.getText());
double dblinterestRate=Double.parseDouble((String)MortCombo.getSelectedItem());
int intTerm=Integer.parseInt(Term.getText());
DecimalFormat money = new DecimalFormat("$0.00");


double MonthlyPayment=0.0;
double InterestPayment=0.0;
double PrincipalBal=0.0;
double MIntRate=dblinterestRate/1200;
int MTerms=intTerm * 12;

//monthly payment formula
MonthlyPayment=(dblprincipal * MIntRate) / (1-Math.pow((MIntRate+1),-MTerms));

//converts Monthly Payment to decimal format
monthlyPayment.setText("" + (money.format(MonthlyPayment)));

MortTextField.append("Month No.ttMonthly PaymenttttLoan BalancetttInterest Paymentn");
MortTextField.append("1ttt" + MonthlyPayment + PrincipalBal + InterestPayment + "n");

//REMOVE "FOR" STATEMENT FOR WEEK 5 HOMEWORK
for (int counter=1; counter < MTerms; counter++)
{
MortTextField.append((counter + 1) + "ttt" + MonthlyPayment + PrincipalBal + InterestPayment + "n");
}

}

private static void createAndShowGui()
{
JFrame frame = new JFrame("Mortgage Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MortgageText myCalculator = new MortgageText();
myCalculator.setOpaque(true);
frame.setContentPane(myCalculator);

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
createAndShowGui();
}
}

);

}



}
//Global Variable
protected JComboBox MortCombo;
protected JLabel lblprincipal, lblinterestRate, lblTerm, lblmonthlyPayment;
protected JButton calculate, Clear;
protected JTextField principal, interestRate, Term, monthlyPayment;
protected TextArea MortTextField;

public MortgageText()
{
String[] comboItems={"5.35","5.50","5.75","10.0"};

//creates labels and fields
lblprincipal=new JLabel("Principal Amount:");
principal = new JTextField("",10);
lblinterestRate=new JLabel("Interest Rate:");
interestRate = new JTextField("",10);
lblTerm=new JLabel("Term:");
Term = new JTextField("",10);
lblmonthlyPayment=new JLabel("Monthly Payment:");
monthlyPayment = new JTextField("",10);
MortCombo=new JComboBox(comboItems);
MortTextField=new TextArea(10,120);

//create buttons
calculate = new JButton("Calculate"); //button used to calculate mortgage payment
calculate.setActionCommand("GO");

Clear = new JButton("Clear"); //button used to clear data from the fields
Clear.setActionCommand("Clear");


//add action to button
calculate.addActionListener(this);
Clear.addActionListener(this);

add(lblprincipal);
add(principal);
add(lblinterestRate);
add(MortCombo);
add(lblTerm);
add(Term);
add(lblmonthlyPayment);
add(monthlyPayment);
add(calculate);
add(Clear);
add(MortTextField);

}
public void actionPerformed(ActionEvent e)
{
if ("GO".equals(e.getActionCommand()))
{
CalculateMortgage();
}
else
{
principal.setText("");
interestRate.setText("");
Term.setText("");
monthlyPayment.setText("");
}
}

// principal.setText(interestRate.getText()); --this will read the interestRate text field and copy it to the principal field

public void CalculateMortgage()
{
double dblprincipal=Double.parseDouble(principal.getText());
double dblinterestRate=Double.parseDouble((String)MortCombo.getSelectedItem());
int intTerm=Integer.parseInt(Term.getText());
DecimalFormat money = new DecimalFormat("$0.00");


double MonthlyPayment=0.0;
double InterestPayment=0.0;
double PrincipalBal=0.0;
double MIntRate=dblinterestRate/1200;
int MTerms=intTerm * 12;

//monthly payment formula
MonthlyPayment=(dblprincipal * MIntRate) / (1-Math.pow((MIntRate+1),-MTerms));

//converts Monthly Payment to decimal format
monthlyPayment.setText("" + (money.format(MonthlyPayment)));

MortTextField.append("Month No.ttMonthly PaymenttttLoan BalancetttInterest Paymentn");
MortTextField.append("1ttt" + MonthlyPayment + PrincipalBal + InterestPayment + "n");

//REMOVE "FOR" STATEMENT FOR WEEK 5 HOMEWORK
for (int counter=1; counter < MTerms; counter++)
{
MortTextField.append((counter + 1) + "ttt" + MonthlyPayment + PrincipalBal + InterestPayment + "n");
}

}

private static void createAndShowGui()
{
JFrame frame = new JFrame("Mortgage Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MortgageText myCalculator = new MortgageText();
myCalculator.setOpaque(true);
frame.setContentPane(myCalculator);

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
createAndShowGui();
}
}

);

}



}
answered by: mchawk
Add a comment
Answer #4
import java.io.*;
import java.text.DecimalFormat;

public class mortgagepaymentweek4 {
public static void main(String[] args) throws IOException {
int startNum, lineCtr, ctr, numMortgages;

// initalize the year array. This will be a 3 index array with the
// values
// 7, 15, and 30 at indexes 0, 1, and 2 respectively
int lastNum[] = { 7, 15, 30 };
int maxLineCtr = 25;
double initAmt, begYearAmt, endYearAmt, intThisYear, cumInterest;

// initialize the interest rates in the same manner as the years
double intRate[] = { 0.0535, 0.055, 0.0575 };
String nothing;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(
System.in));
DecimalFormat twoDigits = new DecimalFormat("0.00");

// grab the number of mortgages we are comparing, in this case 3
numMortgages = lastNum.length;
lineCtr = 1;

// start a for loop in order to loop through our array of mortgages
for (int arrayIndex = 0; arrayIndex < numMortgages; arrayIndex++) {

// initialize amount and rates, we need to do this in each iteration
// of the array loop in order to not use old data where we shouldn't
initAmt = 200000.00;
// intRate = .0575;
begYearAmt = initAmt;
cumInterest = 0.00;

// compute the monthly payments using the standard mortgage
// formula
double i = intRate[arrayIndex] / 12;
int n = lastNum[arrayIndex] * 12;
double monthlyPayment = initAmt
* ((i * Math.pow((1 + i), n)) / (Math.pow((1 + i), n) - 1));

// print monthly payments
System.out
.println("----------------------------------------------------------------------------");
System.out.println(+ lastNum[arrayIndex]
+ " years at " + (intRate[arrayIndex] * 100) + "% with $"
+ twoDigits.format(monthlyPayment)
+ " monthly payment");
} // end for
// System.out.println("line ctr is " + line Ctr);
System.out
.println("----------------------------------------------------------------------------");
}// end main

}// end class
answered by: Carleeta
Add a comment
Answer #5
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.image.BufferedImage;

public class MortgagePaymentCalculatorCR7 extends Frame implements ActionListener
{
//Initializing private global variables for the class
private Label lbl;
private Button submit;
private DecimalFormat calcPattern;
private Label lLoan ;
private TextField tLoan;
private Label lTerm;
private TextField tTerm;
private Label lInterestRate;
private TextField tInterestRate;
private Label fLoan;
private Label sLoan;
private Label thLoan;
private Label slbl;
private Button ssubmit;
private Label slLoan ;
private TextField stLoan;
private Label sfLoan;
private Label ssLoan;
private Label sthLoan;
private JRadioButton firstButton;
private JRadioButton secondButton;
private JRadioButton thirdButton;
private double loanInfo[][];
private JTable table;
private JTextArea output;
private Label displayText;
private JCheckBox displayButton;
private Label sdisplayText;
private JCheckBox sdisplayButton;
private Panel firstPanel;
private Panel secondPanel;
private Panel thirdPanel;
private Panel fourthPanel;
private Panel fifthPanel;
private Panel sixthPanel;
private Panel seventhPanel;
private DataInputStream istream;

public MortgagePaymentCalculatorCR7()
{
//Creating All needed panels to hold the different displays
firstPanel = new Panel();
secondPanel = new Panel();
thirdPanel = new Panel();
fourthPanel = new Panel();
fifthPanel = new Panel();
sixthPanel = new Panel();
seventhPanel = new Panel();
//Creating and Adding the Menu to the form
menuDisplay();
//Creating a WindowListener
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
//Filling Panel Displays with all of the needed Objects and adding panels to the form
add(selectDisplay(fifthPanel),BorderLayout.NORTH);
add(textDisplay(secondPanel),BorderLayout.NORTH);
//Creating the Layout for the chart image then drawing the chart
sixthPanel.setLayout(new FlowLayout());
//Creating and Initializing all of the variables for the chart image display
String mortgage = new String(" % Mortgage");
String mPayment = new String(" % Monthly Payment");
String iPayment = new String(" % Interest Payment");
String mHeading = new String(" Mortgage Chart");
Font hell2Font = new Font("Helvetica", Font.ITALIC, 14);
BufferedImage image=new BufferedImage(200,400,BufferedImage.TYPE_INT_ARGB);
JLabel label=new JLabel(new ImageIcon(image));
Graphics pen = image.getGraphics();
//Drawing a pie chart and a legend
//Creating all parts of the pie chart and legend in blue
pen.setColor(Color.blue);
pen.fillArc(10,50,100,100,45,270);
pen.fillRect(10,175,10,10);
//Creating all parts of the pie chart and legend in green
pen.setColor(Color.green);
pen.fillArc(10,50,100,100,340,65);
pen.fillRect(10,190,10,10);
//Creating all parts of the pie chart and legend in yellow
pen.setColor(Color.yellow);
pen.fillArc(20,57,100,100,315,25);
pen.fillRect(10,205,10,10);
//Writing the words in the legend
pen.setColor(Color.black);
pen.drawString(mortgage,20,185);
pen.drawString(mPayment,20,200);
pen.drawString(iPayment,20,215);
//Creating the Header of the Pie Chart image
pen.setFont(hell2Font);
pen.setColor(Color.blue);
pen.drawString(mHeading,10,10);
//clearing the pen
pen.dispose();
//Adding the drawn images to the display
sixthPanel.add(label);
seventhPanel.setLayout(new GridLayout(0,2,0,10));
seventhPanel.add(sixthPanel);

//Creating and initializing the text area with headings and making it uneditable
String header = "Loan Balance" +" "+ "Interest Paid" + "n";
output = new JTextArea(header,20,20);
output.setEnabled(false);
//Adding third panel to page and adding scroll bars to text area
thirdPanel.add(output, BorderLayout.CENTER);
thirdPanel.add(new JScrollPane(output));
seventhPanel.add(thirdPanel);
add(seventhPanel,BorderLayout.CENTER);
//Creating the array and filling it with data
CreateAndFillArray();
}
public void menuDisplay()
{
// Creating the menu for the application
MenuBar mnuBar = new MenuBar();
setMenuBar(mnuBar);
// Creating the File menu
Menu mnuFile = new Menu("File", true);
mnuBar.add(mnuFile);
MenuItem mnuFileExit = new MenuItem("Exit");
mnuFile.add(mnuFileExit);
// Creating the Edit menu and adding clear option
Menu mnuEdit = new Menu("Edit", true);
mnuBar.add(mnuEdit);
MenuItem mnuEditClear = new MenuItem("Clear");
mnuEdit.add(mnuEditClear);
//Creating the About menu
Menu mnuAbout = new Menu("About", true);
mnuBar.add(mnuAbout);
MenuItem mnuAboutCalculator = new MenuItem("About Mortgage Calculator");
mnuAbout.add(mnuAboutCalculator);
//Adding the ActionListener to each menu item
mnuFileExit.addActionListener(this);
mnuEditClear.addActionListener(this);
mnuAboutCalculator.addActionListener(this);
//Assigning an ActionCommand to each menu item
mnuFileExit.setActionCommand("Exit");
mnuEditClear.setActionCommand("Clear");
mnuAboutCalculator.setActionCommand("About");
}
public Panel textDisplay(Panel secondPanel)
{
//Creating sections to hold the fields, buttons, and labels for display
//Makes better layout for form items
firstPanel = new Panel();
displayText = new Label("");
displayButton = new JCheckBox("Available Mortgages");
lbl = new Label("");
lLoan = new Label("Mortgage Amount");
tLoan = new TextField(20);
lTerm = new Label("Mortgage Term in Years");
tTerm = new TextField(20);
lInterestRate = new Label("Interest Rate % per year");
tInterestRate =new TextField(20);
submit = new Button("Calculate Monthly Payment");
tLoan.setText("");
tTerm.setText("");
tInterestRate.setText("");
//Setting the layout for the panels of the labels and text fields
firstPanel.setLayout(new GridLayout(8,2,30,10));
firstPanel.add(displayButton);
firstPanel.add(displayText);
firstPanel.add(lLoan);
firstPanel.add(tLoan);
firstPanel.add(lTerm);
firstPanel.add(tTerm);
firstPanel.add(lInterestRate);
firstPanel.add(tInterestRate);
//Setting Action command and ActionListener for form submit button and display button
submit.setActionCommand("Calculate");
submit.addActionListener(this);
displayButton.setActionCommand("Select");
displayButton.addActionListener(this);
//Adding the form button and label that will display the Monthly payment results to the user to the form
firstPanel.add(submit);
firstPanel.add(lbl);
secondPanel.add(firstPanel);
return secondPanel;
}
public Panel selectDisplay(Panel fifthPanel)
{
//Creating sections to hold the fields, buttons, and labels for display
//Makes better layout for form items
fourthPanel = new Panel();
sdisplayText = new Label("");
sdisplayButton = new JCheckBox("Available Mortgages");
slbl = new Label("");
slLoan = new Label("Mortgage Amount");
stLoan = new TextField(20);
sfLoan = new Label("First Mortgage");
ssLoan = new Label("Second Mortgage");
sthLoan = new Label("Third Mortgage");
ssubmit = new Button("Calculate Monthly Payment");
stLoan.setText("");
//Creating and initializing radio buttons
firstButton = new JRadioButton("7 years at 5.35%");
firstButton.setSelected(true);
secondButton = new JRadioButton("15 years at 5.5%");
secondButton.setSelected(false);
thirdButton = new JRadioButton("30 years at 5.75%");
thirdButton.setSelected(false);
//Adding radio buttons to a group so they work together and only one can be selected at a time.
ButtonGroup bGroup = new ButtonGroup();
bGroup.add(firstButton);
bGroup.add(secondButton);
bGroup.add(thirdButton);
//Setting the layout for the panels of the labels and text fields
//firstPanel.removeAll();
fourthPanel.setLayout(new GridLayout(8,2,30,10));
fourthPanel.add(sdisplayButton);
fourthPanel.add(sdisplayText);
fourthPanel.add(slLoan);
fourthPanel.add(stLoan);
fourthPanel.add(sfLoan);
fourthPanel.add(firstButton);
fourthPanel.add(ssLoan);
fourthPanel.add(secondButton);
fourthPanel.add(sthLoan);
fourthPanel.add(thirdButton);
//Adding the form button and label that will display the Monthly payment results to the user to the form
fourthPanel.add(ssubmit);
fourthPanel.add(slbl);
//Setting Action command and ActionListener for form submit button
ssubmit.setActionCommand("MCalculate");
ssubmit.addActionListener(this);
sdisplayButton.setActionCommand("Select");
sdisplayButton.addActionListener(this);
fifthPanel.add(fourthPanel);
return fifthPanel;
}
public void actionPerformed(ActionEvent e)
{
//Catching user actions
String arg = e.getActionCommand();
//When Exit is selected close program
if(arg == "Exit")
System.exit(0);
//When Clear is selected clear all of the text fields and display label, then set focus on the mortgage field.
if(arg == "Clear")
{
stLoan.setText("");
firstButton.setSelected(true);
slbl.setText("");
stLoan.requestFocus();
tLoan.setText("");
tTerm.setText("");
tInterestRate.setText("");
lbl.setText("");
tLoan.requestFocus();
}
//When About is selected display message popup window
if(arg == "About")
{
String message = "Mortgage Calculator ver. 4.0nBarnett SoftwarenCopyright 2009nAll rights reserved";
JOptionPane.showMessageDialog(null, message,"About Mortgage Calculator", JOptionPane.INFORMATION_MESSAGE);
}
//When the checkbox is selected change the display
if (arg == "Select")
{
//When the checkbox is checked display the menu of mortgages
if(displayButton.isSelected())
{
//Adding the panel that contains the menu of mortgages to the form
add(fifthPanel,BorderLayout.NORTH);
remove(secondPanel);
displayButton.setSelected(false);
//reset all of the fields of the Panel that has just been added
stLoan.setText("");
firstButton.setSelected(true);
slbl.setText("");
stLoan.requestFocus();
}
else //When the checkbox is not checked display the text fields for free entry of Mortgages
{
//Adding the panel that contains the text fields for free entry
add(secondPanel,BorderLayout.NORTH);
remove(fifthPanel);
//Reset all of the fields of the panel that has just been added
tLoan.setText("");
tTerm.setText("");
tInterestRate.setText("");
lbl.setText("");
tLoan.requestFocus();
}
//Clearing the text area and resetting it
output.setText("");
output.setText(" Loan Balance" +" "+ "Interest Paid" + "n");
output.setRows(0);
output.setRows(20);
//Redrawing the screen
invalidate();
validate();
}
//When the Calculate button is selected calculate the user's input and display the monthly payment of the mortgage.
if(arg == "Calculate")
{
// Declaring all variables
int iLoan;
int years;
int months;
double loan;
double interest;
double interestRate;
double nPayments;
double pTemp;
double nTemp;
double monthlyPayment;

try
{
//Testing data received by user to see if it can be converted to numerical data
//If not then displaying a message to the user
loanInfo[3][3] = Double.parseDouble(tLoan.getText());
loanInfo[3][0] = Double.parseDouble(tTerm.getText());
loanInfo[3][1] = Double.parseDouble(tInterestRate.getText());
iLoan = 3;
//When data received by user contains numeric data checking to see if the data is greater than zero
//if not then displaying a message to the user
if(loanInfo[3][3] > 0 &&loanInfo[3][0] > 0 &&loanInfo[3][1] > 0)
{
years = (int)loanInfo[iLoan][0];
months = 12;
loan = loanInfo[3][3];
interest = loanInfo[iLoan][1]/100;
//Setting format of data for display
calcPattern = new DecimalFormat("########.##");
// Performing calculations on user input data to get the "monthly payment amount".
interestRate = interest/months;
nPayments = -(months * years);
pTemp = loan * interestRate;
nTemp = 1 - Math.pow((1 + interestRate), nPayments);
monthlyPayment = pTemp/nTemp;
loanInfo[iLoan][2] = monthlyPayment;
//Displaying the monthly payment amount to the user
lbl.setText(" $ " + calcPattern.format(monthlyPayment));
//Calling method for calculating loan balance and interest paid then displaying the results
CalculateLoanInt(iLoan,loanInfo);
}
else
{
//Message displayed to user if the input value is <= 0
lbl.setText("Input values greater than 0");
}
}
catch(Throwable exc)
{
//Message displayed to user if the input data is not a number
lbl.setText("Input numeric values only");
}
}
//When the Calculate button is selected calculate the user's input and display the monthly payment of the mortgage.
if(arg == "MCalculate")
{
// Declaring all variables
int iLoan;
int years;
int months;
double loan;
double interest;
double interestRate;
double nPayments;
double pTemp;
double nTemp;
double monthlyPayment;
try
{
//Testing data received by user to see if it can be converted to numerical data
//If not then displaying a message to the user
loanInfo[3][3] = Double.parseDouble(stLoan.getText());
//When data received by user contains numeric data checking to see if the data is greater than zero
//if not then displaying a message to the user
if(loanInfo[3][3] > 0)
{
iLoan = 0;
// Initializing variables with user input data
if(firstButton.isSelected())
iLoan = 0;
if(secondButton.isSelected())
iLoan = 1;
if(thirdButton.isSelected())
iLoan = 2;
years = (int)loanInfo[iLoan][0];
months = 12;
loan = loanInfo[3][3];
interest = loanInfo[iLoan][1]/100;
//Setting format of data for display
calcPattern = new DecimalFormat("########.##");
// Performing calculations on user input data to get the "monthly payment amount".
interestRate = interest/months;
nPayments = -(months * years);
pTemp = loan * interestRate;
nTemp = 1 - Math.pow((1 + interestRate), nPayments);
monthlyPayment = pTemp/nTemp;
loanInfo[iLoan][2] = monthlyPayment;
//Displaying the monthly payment amount to the user
slbl.setText(" $ " + calcPattern.format(monthlyPayment));
//Calling method for calculating loan balance and interest paid then displaying the results
CalculateLoanInt(iLoan,loanInfo);
}
else
{
//Message displayed to user if the input value is <= 0
slbl.setText("Input values greater than 0");
}
}
catch(Throwable exc)
{
//Message displayed to user if the input data is not a number
slbl.setText("Input numeric values only");
}
}
}
//Initializing variables to calculate loan balance and interest paid.(interest paid = P*r*t)
public double[][] CalculateLoanInt(int iLoan, double loanInfo[][])
{
double time;
double loanBalance;
double interestPaid;
double principalPaid;
double loanInterestInfo[][];
int iTerm;
int numPayments;
//Initializing variables for calculations
time = .083333; //time = 1/12
loanBalance = loanInfo[3][3];
interestPaid = loanInfo[3][3] * (loanInfo[iLoan][1]/100) * time;
numPayments = (int)loanInfo[iLoan][0] * 12;
loanInterestInfo = new double[numPayments][2];
iTerm = 0;
//Calculating the loan balance and interest paid for each monthly payment made over term of loan
//putting that information in a two dimensional array.
for(iTerm = 0; iTerm < numPayments; iTerm++)
{
interestPaid = loanBalance * (loanInfo[iLoan][1]/100) * time;
principalPaid = loanInfo[iLoan][2] - interestPaid;
loanBalance = loanBalance - principalPaid;
if (loanBalance < 0) loanBalance = 0;
loanInterestInfo[iTerm][0] = loanBalance;
loanInterestInfo[iTerm][1] = interestPaid;
}
//Setting format of data for display
calcPattern = new DecimalFormat("$ ##,###,###.##");
//Initializing variables and clearing text area and setting rows for text area based on loan
iTerm = 0;
output.setText("");
output.setText(" Loan Balance" +" "+ "Interest Paid" + "n");
output.setRows(numPayments);
//Displaying the loan balance and interest paid for each monthly payment made over term of loan
for(iTerm = 0; iTerm < numPayments; iTerm++)
{
output.append(" "+calcPattern.format(loanInterestInfo[iTerm][0])+" "+calcPattern.format(loanInterestInfo[iTerm][1])+"" + "n");
}
return loanInterestInfo;
}
public void CreateAndFillArray()
{
//Creating and initializing an array to hold mortgage data
int iRate;
loanInfo = new double[4][4];
// Filling array years for mortgage menu
loanInfo[0][0] = 7;
loanInfo[1][0] = 15;
loanInfo[2][0] = 30;
try
{
istream = new DataInputStream(new FileInputStream("interest.dat"));
}
catch(IOException e)
{
System.err.println("File not opened");
System.exit(1);
}
try
{
//Filling array with interest rates from a sequential file
for(iRate = 0; iRate < 3; iRate++)
{
loanInfo[iRate][1] = istream.readDouble();
}
}
catch(EOFException e2)
{
closeFile();
}
catch(IOException e3)
{
System.err.println("Error reading file");
System.exit(1);
}
}
public void closeFile()
{
try
{
istream.close();
System.exit(0);
}
catch(IOException e)
{
System.err.println("Error closing file");
System.exit(1);
}
}
public static void main(String[] args)
{
//Creating an instance of the Mortgage calculator
MortgagePaymentCalculatorCR7 mCal = new MortgagePaymentCalculatorCR7();
//Setting the mortgage calculator title, size and making it visible to the user
mCal.setTitle("Mortgage Calculator");
mCal.setSize(550,700);
mCal.setVisible(true);
}
}
answered by: Karen Ms.Sue
Add a comment
Know the answer?
Add Answer to:
Java Programming----- Creating a Mortgage Calculator Program
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ programming For this assignment, write a program that will act as a geometry calculator. The...

    C++ programming For this assignment, write a program that will act as a geometry calculator. The program will be menu-driven and should continue to execute as long as the user wants to continue. Basic Program Logic The program should start by displaying a menu similar to the following: Geometry Calculator 1. Calculate the area of a circle 2. Calculate the area of a triangle 3. Quit Enter your choice(1-3): and get the user's choice as an integer. After the choice...

  • Using Java Eclipse with comments: The main purpose of this programming assignment is for students to...

    Using Java Eclipse with comments: The main purpose of this programming assignment is for students to have a deep understanding of how to implement Heapsort algorithm. 1.1 Details l Implement Heapsort algorithm; run the program on two different manners: 1)      Ask the user to select a number (the array size x); also ask the user to provide all x elements in the user interface; display this user-supplied array BOTH before AND after sorting. 2)      Ask the user to select an...

  • Program Specification: This project involves implementing a Java program that performs a calculation of payments associated...

    Program Specification: This project involves implementing a Java program that performs a calculation of payments associated with loans. The program shall allow a user to enter the following data: annual interest rate the loan (i.e. , number of years), and the loan amount. A GUI like the one below must be used. Loan Calculator Annual Interest Rate: Number of Years Loan Amount: Monthly Payment Total Payment Calculate When the user presses the calculate button, the monthly payment and total amount...

  • Overview Module 3 Assignment 2 features designing a program using pseudocode and then completing the program...

    Overview Module 3 Assignment 2 features designing a program using pseudocode and then completing the program in Python using strings. M3Lab2 asks you to write a Mortgage Loan Calculator. Each lab asks you to write pseudocode that plans the program’s logic before you write the program in Python and to turn in three things: 1) the pseudocode, 2) a screenshot of the output, and 3) the Python program. Instructions Pseudocode and Python Program with Strings M3Lab2.txt has some of the...

  • I have to use java programs using netbeans. this course is introduction to java programming so...

    I have to use java programs using netbeans. this course is introduction to java programming so i have to write it in a simple way using till chapter 6 (arrays) you can use (loops , methods , arrays) You will implement a menu-based system for Hangman Game. Hangman is a popular game that allows one player to choose a word and another player to guess it one letter at a time. Implement your system to perform the following tasks: Design...

  • I've created a mortgage calculator and the next step in my project is to include an...

    I've created a mortgage calculator and the next step in my project is to include an array. I'm not very good at C++ as this is my first time taking a programming course. I was able to get this working but I'm confused as to where I could use an array. I was thinking of maybe using the person's credit score as an indication of what their interest rate could be for a HELOC. Something like this : int creditScore[3]={2.8,...

  • c++ and please add tables and everything and make sure program is complete. Write a menu...

    c++ and please add tables and everything and make sure program is complete. Write a menu driven program, which would compute compound interest and a monthly payment for a loan. The user will be given a choice to display the info on the screen or to a filo Menu will be the following Enter (1) to calculate your loan monthly payment Enter (2) to calculate your loan monthly payment & write to a file Tips: Compound Interest Formula A =...

  • 6. Loan Calculator The e most common types of loans are mortgage loans, which are tinance...

    6. Loan Calculator The e most common types of loans are mortgage loans, which are tinance the purchase of a house, and car loans. A loan consists of four com- L1 ponents--amount, interest rate, duration, and periodic payment. The purpose values of the other three components. prograrmming project is to calculate the value of any one of the components given the We will ascurme that the duration is in months, that interest (given as a percent) i gages typically have...

  • The program is in python :) Write a code program to calculate the mortgage payment. The...

    The program is in python :) Write a code program to calculate the mortgage payment. The equation for calculating the mortgage payment is: M = P (1+r)n (1+r)n-1 Where: M is your monthly payment P is your principal r is your monthly interest rate, calculated by dividing your annual interest rate by 12. n is your number of payments (the number of months you will be paying the loan) Example: You have a $100,000 mortgage loan with 6 percent annual...

  • THIS IS FOR C++ PROGRAMMING USING VISUAL STUDIO THE PROGRAM NEEDS TO BE IN C++ PROGRAMMING #inclu...

    THIS IS FOR C++ PROGRAMMING USING VISUAL STUDIO THE PROGRAM NEEDS TO BE IN C++ PROGRAMMING #include "pch.h" #include #include using namespace std; // Function prototype void displayMessage(void); void totalFees(void); double calculateFees(int); double calculateFees(int bags) {    return bags * 30.0; } void displayMessage(void) {    cout << "This program calculates the total amount of checked bag fees." << endl; } void totalFees() {    double bags = 0;    cout << "Enter the amount of checked bags you have." << endl;    cout <<...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT