Mortgage Calculator with user input

I am getting unusual output only when calculating with user input

Page 1 of 1

3 Replies - 6236 Views - Last Post: 21 March 2008 - 04:39 PM Rate Topic: -----

#1 JSticht  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-March 08

Mortgage Calculator with user input

Post icon  Posted 17 March 2008 - 08:17 PM

The 3 buttons with pre-determined mortgage terms and rates work. It will not work with user input. All of the values come out as boxes. Please help. Thanks.

 /*
		Week 4: 	Payment Calculator
		Programmer:	Jeff Sticht
		Date:		March 17, 2008
		Filename:	newCalc.java
		Purpose:	This program will allow the user to chose a loan
					and enter the loan ammount or enter their own term and rate.
*/


import java.text.*;
import java.math.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class newCalc
{
	public static void main (String[] args)
	{
		JFrame window = new MortCalcGUI();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setVisible(true);
	}
}

class MortCalcGUI extends JFrame implements ActionListener
{
	//declare GUI function variables and protects them
	protected JButton bCalc7, bCalc15, bCalc30, bClear, bExit, bCalcOwn;
	protected JLabel labelPayment, labelLoanAmount, labelTitle, labelInstructions, labelAmortTable, labelTerm, labelRate;
	protected JTextField fieldPayment, fieldLoanAmount, fieldTerm, fieldRate;
	protected JTextArea areaAmortTable;


	//Declare variables
	double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount;
	int[] loanTerm = {7,15,30}; // loan term
	double[] intRate = {5.35,5.50,5.75}; // interest rates
	double loanAmt = loanAmount;
	double userRate;
	int userTerm;


	public void actionPerformed (ActionEvent e)
	{
		//determines which button was pressed
		if ("Calculate7".equals(e.getActionCommand()))
		{
			DecimalFormat decimalPlaces = new DecimalFormat("0.00");
			NumberFormat currency = NumberFormat.getCurrencyInstance();

			double paymentAmount = CalculatePayment7();


			fieldPayment.setText("" + (currency.format(paymentAmount)));

			areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");


			// set loan amount
			loanAmt = Double.parseDouble(fieldLoanAmount.getText());

			for (int x = 1; x <=(loanTerm[0]*12); x++) //Loop through all monthly payments for each loan
			{

					Balance=loanAmt; //Set Balance to Loan Amount


					//Calculations on monthly payment

					InterestPaid=(((intRate[0]/100.0)/12.0)*Balance); //Monthly Interest paid
					PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
					 loanAmt=(Balance-PrinciplePaid); //loan balance after payment


					areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");

			}


			if (Balance <= 0) //ending statement
			{
				areaAmortTable.append ("\tRemaining balance = $0.00");
			}
	   }

		else if ("Calculate15".equals(e.getActionCommand()))
		{
			DecimalFormat decimalPlaces = new DecimalFormat("0.00");
			NumberFormat currency = NumberFormat.getCurrencyInstance();

			double paymentAmount = CalculatePayment15 ();

			fieldPayment.setText("" + (currency.format(paymentAmount)));


			areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
			loanAmt = Double.parseDouble(fieldLoanAmount.getText());

			for (int x = 1; x <=(loanTerm[1]*12); x++) //Loop through all monthly payments for each loan
			{

					Balance = loanAmt;

					//Calculations on monthly payment
					InterestPaid=((intRate[1]/100/12)*Balance); //Monthly Interest paid
					PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
					loanAmt=((Balance-PrinciplePaid)); //loan balance after payment

					areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
			}

			if (loanAmt <= 0) //ending statement
			{
				areaAmortTable.append ("\tRemaining balance = $0.00");
			}

		}

		else if ("Calculate30".equals(e.getActionCommand()))
		{
			DecimalFormat decimalPlaces = new DecimalFormat("0.00");
			NumberFormat currency = NumberFormat.getCurrencyInstance();

			double paymentAmount = CalculatePayment30 ();

			fieldPayment.setText("" + (currency.format(paymentAmount)));

			areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
			loanAmt = Double.parseDouble(fieldLoanAmount.getText());


			for (int x = 1; x <=(loanTerm[2]*12); x++) //Loop through alll monthly payments for each loan
			{
				Balance = loanAmt;

				//Calculations on monthly payment
				InterestPaid=((intRate[2]/100/12)*Balance); //Monthly Interest paid
				PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
				loanAmt=((Balance-PrinciplePaid)); //loan balance after payment

				areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
			}

			if (loanAmt <= 0) //ending statement
			{
				areaAmortTable.append ("\tRemaining balance = $0.00");
			}

		}

		else if ("Calculate".equals(e.getActionCommand()))
				{
					DecimalFormat decimalPlaces = new DecimalFormat("0.00");
					NumberFormat currency = NumberFormat.getCurrencyInstance();

					double paymentAmount = CalculatePayment ();

					fieldPayment.setText("" + (currency.format(paymentAmount)));


					areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
					loanAmt = Double.parseDouble(fieldLoanAmount.getText());
					userTerm = Integer.parseInt(fieldTerm.getText());
					userRate = Double.parseDouble(fieldRate.getText());

					for (int x = 1; x <=(userTerm*12); x++) //Loop through all monthly payments for each loan
					{

							Balance = loanAmt;

							//Calculations on monthly payment
							InterestPaid=((userRate/100/12)*Balance); //Monthly Interest paid
							PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
							loanAmt=((Balance-PrinciplePaid)); //loan balance after payment

							areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
					}

					if (loanAmt <= 0) //ending statement
					{
						areaAmortTable.append ("\tRemaining balance = $0.00");
					}

		}

		else if ("Clear".equals(e.getActionCommand()))
		{
			ClearFields ();
		}

		else
		{
			//exit application
			System.exit(0);
	   }
	}

	public double CalculatePayment7 ()
	{

		//Check for valid numeric imput
		try
		{
			//Perform payment calculations if input is valid

			fieldPayment.setText ("");
			double Payment =(loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)),loanTerm[0]*12));
			return Payment;
		}

		catch (NumberFormatException event)
		{
			//Display error message if input is invalid
			JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment15 ()
	{
		//Check for valid numeric imput
		try
		{
			//Perform payment calculations if input is valid
			fieldPayment.setText ("");
			double Payment =(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)),loanTerm[1]*12));
			return Payment;
		}

		catch (NumberFormatException event)
		{
			//Display error message if input is invalid
			JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment30 ()
	{
		//Check for valid numeric imput
		try
		{
			//Perform payment calculations if input is valid
			fieldPayment.setText ("");
			double Payment =(loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)),loanTerm[2]*12));
			return Payment;
		}

		catch (NumberFormatException event)
		{
			//Display error message if input is invalid
			JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment ()
		{
			//Check for valid numeric imput
			try
			{
				//Perform payment calculations if input is valid
				fieldPayment.setText ("");
				double Payment =(loanAmount() * (userRate/100/12)) / (1 - Math.pow(1/(1 + (userRate/100/12)),userTerm*12));
				return Payment;
			}

			catch (NumberFormatException event)
			{
				//Display error message if input is invalid
				JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
				return 0;
			}
		}



	public void ClearFields ()
	{
		//Set all text fields to blank
		fieldPayment.setText ("");
		fieldLoanAmount.setText ("");
		areaAmortTable.setText ("");
	}

	public MortCalcGUI ()
	{
		//Set up and initialize buttons for GUI
		bCalc7 = new JButton ("7 Year, 5.35%");
		bCalc7.setActionCommand ("Calculate7");
		bCalc15 = new JButton ("15 Year, 5.50%");
		bCalc15.setActionCommand ("Calculate15");
		bCalc30 = new JButton ("30 Year, 5.75%");
		bCalc30.setActionCommand ("Calculate30");
		bCalcOwn = new JButton ("User Input");
		bCalcOwn.setActionCommand ("Calculate");
		bClear = new JButton ("Clear All Fields");
		bClear.setActionCommand ("Clear");
		bExit = new JButton ("Exit Program");
		bExit.setActionCommand ("Exit");

		//Set up labels and field sizes for GUI
		labelTitle = new JLabel ("New Calculator");
		labelInstructions = new JLabel ("Enter the amount of the loan and then choose the term/rate of the loan or enter your own.");

		labelPayment = new JLabel ("Monthly Payment:");
		labelLoanAmount = new JLabel ("Amount of Loan:");
		labelRate = new JLabel ("Your rate in %:");
		labelTerm = new JLabel ("Your term in Years:");
		fieldPayment = new JTextField ("", 10);
		fieldLoanAmount = new JTextField ("", 10);
		fieldRate = new JTextField ("", 3);
		fieldTerm = new JTextField ("", 3);
		labelAmortTable = new JLabel ("Amortization Table");
		areaAmortTable = new JTextArea (100, 500);

		JScrollPane scrollPane = new JScrollPane (areaAmortTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
		JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

		//Set up listeners for each button
		bCalc7.addActionListener(this);
		bCalc15.addActionListener(this);
		bCalc30.addActionListener(this);
		bCalcOwn.addActionListener(this);
		bClear.addActionListener(this);
		bExit.addActionListener(this);

		//Construct GUI and set layout
		JPanel mine = new JPanel();
		mine.setLayout (null);

		mine.add (labelTitle);
		labelTitle.setBounds (110, 30, 700, 15);

		mine.add (labelInstructions);
		labelInstructions.setBounds (30, 70, 450, 15);

		mine.add (labelLoanAmount);
		labelLoanAmount.setBounds (30, 110, 100, 25);

		mine.add (fieldLoanAmount);
		fieldLoanAmount.setBounds (130, 110, 50, 25);

		mine.add (labelTerm);
		labelTerm.setBounds (200, 110, 140, 25);

		mine.add (fieldTerm);
		fieldTerm.setBounds (340, 110, 50, 25);

		mine.add (labelRate);
		labelRate.setBounds (410, 110, 100, 25);

		mine.add (fieldRate);
		fieldRate.setBounds (510, 110, 50, 25);

		mine.add (bCalc7);
		bCalc7.setBounds (40, 150, 125, 30);

		mine.add (bCalc15);
		bCalc15.setBounds (180, 150, 125, 30);

		mine.add (bCalc30);
		bCalc30.setBounds (320, 150, 125, 30);

		mine.add (bCalcOwn);
		bCalcOwn.setBounds (460, 150, 200, 30);

		mine.add (labelPayment);
		labelPayment.setBounds (130, 200, 100, 25);

		mine.add (fieldPayment);
		fieldPayment.setBounds (240, 200, 100, 25);
		fieldPayment.setEditable (false);

		mine.add (labelAmortTable);
		labelAmortTable.setBounds (180, 250, 300, 25);


		// Add the scrollpane, set its bounds and set the table as not editable.

		mine.add (scrollPane);
		scrollPane.setBounds (50, 280, 400, 270);
		areaAmortTable.setEditable(false);

		mine.add (bClear);
		bClear.setBounds (110, 570, 125, 30);

		mine.add (bExit);
		bExit.setBounds (250, 570, 125, 30);

		this.setContentPane(mine);
		this.pack();
		this.setTitle("New Calculator");

		//Set window size
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(700, 800);
	}
	public double loanAmount ()
	{
		double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
		return loanAmount;
	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Mortgage Calculator with user input

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3093
  • View blog
  • Posts: 19,139
  • Joined: 14-September 07

Re: Mortgage Calculator with user input

Posted 18 March 2008 - 05:17 AM

Weird. I ran it a few times and I only saw the boxes once. Every other time it ran fine.

You do have some other errors though: For example a $5,000 loan over 30 years doesn't stop at zero, it goes into negatives.

For the boxes, the only thing I can think of since I can't reproduce it on command, it is the float point calculations. If a certain computer can't display the values it will show a little box (like if it was written in a language you don't have the pack installed for).
Was This Post Helpful? 0
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5763
  • View blog
  • Posts: 12,577
  • Joined: 16-October 07

Re: Mortgage Calculator with user input

Posted 18 March 2008 - 05:31 AM

You need methods with parameters, which would result in drastically fewer lines of code. You also need no globals. Well, maybe lots fewer. Globals are bad.

This is a pretty good example of how globals can be a problem, actually. In your code, your problem is that this call:

double paymentAmount = CalculatePayment ();



Compes before this call:
userTerm = Integer.parseInt(fieldTerm.getText());
userRate = Double.parseDouble(fieldRate.getText());



So, you have no numbers to work from. You're using CalculatePaymentXX for each possibility. You're doing this because of the globals. This would be much easier if you just passed some parameters around.

e.g.
private double getPayment(int termInYears, double yearlyRate) {
	double payment = 0;
	fieldPayment.setText ("");
	//Check for valid numeric imput
	try {
		double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
		//Perform payment calculations if input is valid
		payment =(loanAmount * (yearlyRate/100/12)) / (1 - Math.pow(1/(1 + (yearlyRate/100/12)),termInYears*12));
	} catch (NumberFormatException event) {
		//Display error message if input is invalid
		JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
	}
	return payment;
}



Now, you can do this:
int userTerm = Integer.parseInt(fieldTerm.getText());
double userRate = Double.parseDouble(fieldRate.getText());
double paymentAmount = getPayment(userTerm, userRate);



You can use the same code for the other three:
// double paymentAmount = CalculatePayment7();
double paymentAmount = getPayment(loanTerm[0], intRate[0]);



You can actually get all four of your cases down to a single, simple, method call.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#4 JSticht  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-March 08

Re: Mortgage Calculator with user input

Posted 21 March 2008 - 04:39 PM

Thanks for the replies. I figured out that if I tabbed out of the box after entering the rate, the boxes did not display.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1