I am having an issue with my program. If I select one of the three calc buttons it works fine and shows the amort table correctly. If I put information in the text fields for amount, interest, and years and hit calculate button I get little boxes in the amort table. I have been looking at it for a while and changing things to see if it looks different but it just won't work. Here is my code:

/*
	Week 3 Assignment:			McBride Financial Services Mortgage Calculator
	Programmer:					Robin Spencer
	Filename:							RSpencerMortgageCalcV2.java
	Date:								August 31, 2009
	Purpose:							This program is for change request 5 to take the amount from user input and then have the 			    user select from three different loan payments.
	Cited Source:					http://www.dreamincode.net/forums/showforum32.htm
*/

// import of the packages
import java.text.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class RSpencerMortgageCalculatorV2
{
	public static void main (String[] args)
	{
		JFrame window = new MortCalculation();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setVisible(true);
	}
} // end of class

class MortCalculation extends JFrame implements ActionListener
{
	//delcare function variables
	protected JButton button7, button15, button30, buttonClear, buttonQuit, buttonCalc;
	protected JLabel labelMonthlyPay, labelAmount, labelTitle, labelAmortTable, labelTerm, labelRate;
	protected JTextField fieldPayment, fieldamount, fieldyears, fieldinterest;
	protected JTextArea areaAmortTable;

	// declare variables and array and initialize the values
	double InterestPaid, PrinciplePaid, Balance, monthlyPay, loanAmount, interest;
	int[] loanYears = {7,15,30};
	double[] intRate = {5.35, 5.50, 5.75};
	double loanAmt = loanAmount;
	int years;


	public void actionPerformed (ActionEvent e)
	{
		// perform based on 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");

			// need to set loan amount to the value from the field first which will need to be done for each loan calculations
			loanAmt = Double.parseDouble(fieldamount.getText());

			for(int x = 1; x <=(loanYears[0]*12); x++) // loop through all monthly payment 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 principal
				loanAmt=(Balance-PrinciplePaid); // loan balance after payment

				areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n"); // add to amort table
			} // end for
		} // end first if for button pressed

		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(fieldamount.getText());

			for (int x = 1; x <=(loanYears[1]*12); x++) // loop through all monthly payment for each loan
			{
				Balance = loanAmt; // set balance to loan amount

				// calculations for monthly payment
				InterestPaid=((intRate[1]/100/12)*Balance);
				PrinciplePaid=(paymentAmount-InterestPaid);
				loanAmt=((Balance-PrinciplePaid));

				areaAmortTable.append(x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n"); // add to amort table
			} // end for loop
		} // end else if

		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(fieldamount.getText());

			for(int x = 1; x <=(loanYears[2]*12); x++) // loop through all monthly payment for each loan
			{
				Balance = loanAmt; // set balance to loan amt

				// calculations for monthly payment
				InterestPaid = ((intRate[2]/100/12)*Balance);
				PrinciplePaid = (paymentAmount-InterestPaid);
				loanAmt=((Balance-PrinciplePaid));

				areaAmortTable.append(x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n"); // add to amort table
			} // end for loop
		} // end else if

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

			loanAmt = Double.parseDouble(fieldamount.getText());
			int years = Integer.parseInt(fieldyears.getText());
			double interest = Double.parseDouble(fieldinterest.getText());

			double paymentAmount = Calc();

			fieldPayment.setText("" + (currency.format(paymentAmount)));
			areaAmortTable.append("Payment # \t Remaining Balance \t Interest Paid\n");



			for(int x = 1; x <=(years*12); x++)
			{
				Balance=loanAmt;

				InterestPaid = (((interest/100.00)/12.0)*Balance);
				PrinciplePaid = (paymentAmount-InterestPaid);
				loanAmt = (Balance-PrinciplePaid);

				areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n");
			}
		}
		else if ("Clear".equals(e.getActionCommand()))
		{
			ClearFields(); // action command for reset button
		}
		else if ("Quit".equals(e.getActionCommand()))
		{
			System.exit(0); // action command for quit button
		}
	}

	public double CalculatePayment7()
	{
		// check for valid numbers
		try
		{
			// perform calculations if input is valid
			fieldPayment.setText("");
			double Payment = (loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)), loanYears[0]*12));
			return Payment;
		}

		catch(NumberFormatException event)
		{
			// display error message if not numeric input
			JOptionPane.showMessageDialog(null, " Enter Numeric Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment15()
	{
		try
		{
			fieldPayment.setText("");
			double Payment=(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)), loanYears[1]*12));
			return Payment;
		}

		catch (NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, " Enter Numeric Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment30()
	{
		try
		{
			fieldPayment.setText("");
			double Payment = (loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)), loanYears[2]*12));
			return Payment;
		}
		catch (NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, "Enter Numeric Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double Calc()
	{
		try
		{
			fieldPayment.setText("");
			fieldyears.setText("");
			fieldinterest.setText("");
			double Payment = (loanAmount() * (interest/100/12)) / (1 - Math.pow(1/(1 + (interest/100/12)), years*12));
			return Payment;
		}

		catch(NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public void ClearFields()
	{
		// set all text fields to blank
		fieldPayment.setText ("");
		fieldamount.setText ("");
		areaAmortTable.setText("");
		fieldyears.setText("");
		fieldinterest.setText("");
	}

	public MortCalculation()
	{
		// set up and initialize buttons
		button7 = new JButton("7 years at 5.35%");
		button7.setActionCommand("Calculate7");
		button15 = new JButton("15 years at 5.5%");
		button15.setActionCommand("Calculate15");
		button30 = new JButton("30 years at 5.75%");
		button30.setActionCommand ("Calculate30");
		buttonCalc = new JButton("Calculate");
		buttonCalc.setActionCommand("Calc");
		buttonClear = new JButton("Reset");
		buttonClear.setActionCommand("Clear");
		buttonQuit = new JButton("Quit");
		buttonQuit.setActionCommand("Quit");

		// set up labels and text field sizes
		labelTitle = new JLabel ("Mortgage Calculator");

		labelMonthlyPay = new JLabel("Monthly Payment");
		labelAmount = new JLabel("Amount");
		fieldPayment = new JTextField("", 12);
		fieldamount = new JTextField("", 10);
		labelTerm = new JLabel("Years");
		labelRate = new JLabel("Interest Rate");
		fieldyears = new JTextField("", 12);
		fieldinterest = new JTextField("", 12);
		labelAmortTable = new JLabel("Amortization Table");
		areaAmortTable = new JTextArea(10, 300);

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

		// set up actionlisteners for each button
		button7.addActionListener(this);
		button15.addActionListener(this);
		button30.addActionListener(this);
		buttonCalc.addActionListener(this);
		buttonClear.addActionListener(this);
		buttonQuit.addActionListener(this);

		// construct gui and layout
		JPanel mypanel = new JPanel();
		mypanel.setLayout(null);

		mypanel.add(labelTitle);
		labelTitle.setBounds(150, 20, 500, 15);

		mypanel.add(labelAmount);
		labelAmount.setBounds(130, 60, 80, 25);

		mypanel.add(fieldamount);
		fieldamount.setBounds(240, 60, 100, 25);

		mypanel.add(labelTerm);
		labelTerm.setBounds(130, 85, 80, 40);

		mypanel.add(fieldyears);
		fieldyears.setBounds(240, 90, 100, 25);

		mypanel.add(labelRate);
		labelRate.setBounds(130, 125, 80, 25);

		mypanel.add(fieldinterest);
		fieldinterest.setBounds(240, 125, 100, 25);

		mypanel.add(button7);
		button7.setBounds(35, 170, 130, 30);

		mypanel.add(button15);
		button15.setBounds(180, 170, 130, 30);

		mypanel.add(button30);
		button30.setBounds(320, 170, 135, 30);

		mypanel.add(labelMonthlyPay);
		labelMonthlyPay.setBounds(130, 220, 100, 25);

		mypanel.add(fieldPayment);
		fieldPayment.setBounds(240, 220, 100, 25);
		fieldPayment.setEditable(false);

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

		// add scrollpane, set bounds and set table as not editable
		// table is part of scrollpane now, so add and place only the scrollpane
		mypanel.add(scrollPane);
		scrollPane.setBounds(50, 280, 400, 270);
		areaAmortTable.setEditable(false);

		mypanel.add(buttonCalc);
		buttonCalc.setBounds(50, 570, 100, 30);

		mypanel.add(buttonClear);
		buttonClear.setBounds(170, 570, 95, 30);

		mypanel.add(buttonQuit);
		buttonQuit.setBounds(290, 570, 95, 30);

		this.setContentPane(mypanel);
		this.pack();
		this.setTitle("Mortgage Calculator");

		// set window size
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(500, 700);
	}

	public double loanAmount()
	{
		double loanAmount = Double.parseDouble(fieldamount.getText());
		return loanAmount;
	}
}

Recommended Answers

All 17 Replies

Pay attention to the warnings (commented code added by me. Original has "int", "double" uncommented):

/*int*/ years = Integer.parseInt(fieldyears.getText());
/*double*/ interest = Double.parseDouble(fieldinterest.getText());

Netbeans gives this warning for both lines above:

Local variable hides a field

If you intend "years" and "interest" to be your class-level/field variables, and I think you do, delete "int" and "double" above and recompile and try it again.

Thank you very much it is now working. I am now trying to get it to validate the text fields and it just gives me errors in the command prompt. I can get it to validate for the three loan buttons but not the calculate button. What am I doing wrong?

Thank you very much it is now working. I am now trying to get it to validate the text fields and it just gives me errors in the command prompt. I can get it to validate for the three loan buttons but not the calculate button. What am I doing wrong?

Define "validate" (do you mean "validate" as in re-layout the GUI components or "validate" as far as good versus bad input or what?). What errors do you get? Are they compile errors? Run-time errors? Etc. More details needed.

I get run-time errors. What I am trying to do is to validate that it is numbers put into the text fields when the calculate button is pressed. I get a bunch of errors in the command window when I put anything but numbers in the amount text field. The amount text field is the only one I have tried so far. So it compiles fine and runs and everything works great until I put letters in the amount text field and then I get errors in the command window when it should come up with a window stating that it has to be numeric only.

I get run-time errors. What I am trying to do is to validate that it is numbers put into the text fields when the calculate button is pressed. I get a bunch of errors in the command window when I put anything but numbers in the amount text field. The amount text field is the only one I have tried so far. So it compiles fine and runs and everything works great until I put letters in the amount text field and then I get errors in the command window when it should come up with a window stating that it has to be numeric only.

Do you get a line like this:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "a"

referring to one of your parseInt or parseDouble lines?

Do you get a line like this:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "a"

referring to one of your parseInt or parseDouble lines?

Here is what I get:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For inpu
t string: "kjljj"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12
24)
at java.lang.Double.parseDouble(Double.java:510)
at MortCalculation.actionPerformed(RSpencerMortgageCalculatorV2.java:125
)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
95)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
a:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
istener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574
)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Here is what I get:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For inpu
t string: "kjljj"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12
24)
at java.lang.Double.parseDouble(Double.java:510)

Right. That's that NumberFormatException at a parseDouble line.

http://java.sun.com/javase/6/docs/api/java/lang/Double.html#parseDouble(java.lang.String)

From the link above:

parseDouble

public static double parseDouble(String s)
                          throws NumberFormatException

    Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

    Parameters:
        s - the string to be parsed. 
    Returns:
        the double value represented by the string argument. 
    Throws:
        NumberFormatException - if the string does not contain a parsable double.
    Since:
        1.2
    See Also:
        valueOf(String)

Letters can't be parsed into a double. That's what you're checking for, after all. parseDouble throws an Exception (NumberFormatException to be precise) when it tries to parse a String that has letters in it.

If you don't "catch" that Exception in the code, the program aborts. You need to catch it and tell Java what you want to do when that happens (in this case, probably just a pop-up saying they gave bad input):

try
{
    // put your parsing and calculation code here
}
catch (NumberFormatException ex)
{
    // error message.  Have a pop-up tell them they entered bad input.
}

http://java.sun.com/docs/books/tutorial/essential/exceptions/

Right. That's that NumberFormatException at a parseDouble line.

http://java.sun.com/javase/6/docs/api/java/lang/Double.html#parseDouble(java.lang.String)

From the link above:

parseDouble

public static double parseDouble(String s)
                          throws NumberFormatException

    Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

    Parameters:
        s - the string to be parsed. 
    Returns:
        the double value represented by the string argument. 
    Throws:
        NumberFormatException - if the string does not contain a parsable double.
    Since:
        1.2
    See Also:
        valueOf(String)

Letters can't be parsed into a double. That's what you're checking for, after all. parseDouble throws an Exception (NumberFormatException to be precise) when it tries to parse a String that has letters in it.

If you don't "catch" that Exception in the code, the program aborts. You need to catch it and tell Java what you want to do when that happens (in this case, probably just a pop-up saying they gave bad input):

try
{
    // put your parsing and calculation code here
}
catch (NumberFormatException ex)
{
    // error message.  Have a pop-up tell them they entered bad input.
}

http://java.sun.com/docs/books/tutorial/essential/exceptions/

Isn't that what I am doing here or am I just not looking at it right?

public double Calc()
	{
		try
		{
			fieldPayment.setText("");
			double Payment = (loanAmount() * (interest/100/12)) / (1 - Math.pow(1/(1 + (interest/100/12)), years*12));
			return Payment;
		}

		catch(NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

Isn't that what I am doing here or am I just not looking at it right?

public double Calc()
	{
		try
		{
			fieldPayment.setText("");
			double Payment = (loanAmount() * (interest/100/12)) / (1 - Math.pow(1/(1 + (interest/100/12)), years*12));
			return Payment;
		}

		catch(NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

You need to put the code that throws the NumberFormatException in the try statement (parseDouble and parseInt). The try needs to happen BEFORE the Calc () function because that's where the bad input is parsed and the Exception is thrown. By the time Calc () is called (and Calc () never WILL be called), it's too late. You already have an unhandled Exception. Do this in your actionPerformed:

try
{
	loanAmt = Double.parseDouble(fieldamount.getText());
	years = Integer.parseInt(fieldyears.getText());
	interest = Double.parseDouble(fieldinterest.getText());
}
catch(NumberFormatException event)
{
	JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
	return; // plain old "return" since it's in actionPerformed
}

You need to put the code that throws the NumberFormatException in the try statement (parseDouble and parseInt). The try needs to happen BEFORE the Calc () function because that's where the bad input is parsed and the Exception is thrown. By the time Calc () is called (and Calc () never WILL be called), it's too late. You already have an unhandled Exception. Do this in your actionPerformed:

try
{
	loanAmt = Double.parseDouble(fieldamount.getText());
	years = Integer.parseInt(fieldyears.getText());
	interest = Double.parseDouble(fieldinterest.getText());
}
catch(NumberFormatException event)
{
	JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
	return; // plain old "return" since it's in actionPerformed
}

You are great it is now working. The only other thing is what do I do with the one that I posted earlier because if I take that out it gives me a compile error that it cannot find symbol? I hope I am explaining this right. I just don't want to get points taken off if I have it in there twice.

You are great it is now working. The only other thing is what do I do with the one that I posted earlier because if I take that out it gives me a compile error that it cannot find symbol? I hope I am explaining this right. I just don't want to get points taken off if I have it in there twice.

Post the updated code, along with any error messages. I don't see the need for any try or catch in Calc (). As far as the error, without seeing the revised code and where you put everything, I'd have to speculate, but one possibility is that you have a variable declared inside of a try statement, then you attempt to use it outside of the try statement and it has gone out of scope.

Again, that's speculation. I'd have to see the revised code.

// import of the packages
import java.text.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class RSpencerMortgageCalculatorV3
{
	public static void main (String[] args)
	{
		JFrame window = new MortCalculation();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setVisible(true);
	}
} // end of class

class MortCalculation extends JFrame implements ActionListener
{
	//delcare function variables
	protected JButton button7, button15, button30, buttonClear, buttonQuit, buttonCalc;
	protected JLabel labelMonthlyPay, labelAmount, labelTitle, labelAmortTable, labelTerm, labelRate;
	protected JTextField fieldPayment, fieldamount, fieldyears, fieldinterest;
	protected JTextArea areaAmortTable;

	// declare variables and array and initialize the values
	double InterestPaid, PrinciplePaid, Balance, monthlyPay, loanAmount, interest;
	int[] loanYears = {7,15,30};
	double[] intRate = {5.35, 5.50, 5.75};
	double loanAmt = loanAmount;
	int years;


	public void actionPerformed (ActionEvent e)
	{
		// perform based on 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");

			// need to set loan amount to the value from the field first which will need to be done for each loan calculations
			loanAmt = Double.parseDouble(fieldamount.getText());

			for(int x = 1; x <=(loanYears[0]*12); x++) // loop through all monthly payment 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 principal
				loanAmt=(Balance-PrinciplePaid); // loan balance after payment

				areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n"); // add to amort table
			} // end for
		} // end first if for button pressed

		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(fieldamount.getText());

			for (int x = 1; x <=(loanYears[1]*12); x++) // loop through all monthly payment for each loan
			{
				Balance = loanAmt; // set balance to loan amount

				// calculations for monthly payment
				InterestPaid=((intRate[1]/100/12)*Balance);
				PrinciplePaid=(paymentAmount-InterestPaid);
				loanAmt=((Balance-PrinciplePaid));

				areaAmortTable.append(x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n"); // add to amort table
			} // end for loop
		} // end else if

		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(fieldamount.getText());

			for(int x = 1; x <=(loanYears[2]*12); x++) // loop through all monthly payment for each loan
			{
				Balance = loanAmt; // set balance to loan amt

				// calculations for monthly payment
				InterestPaid = ((intRate[2]/100/12)*Balance);
				PrinciplePaid = (paymentAmount-InterestPaid);
				loanAmt=((Balance-PrinciplePaid));

				areaAmortTable.append(x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n"); // add to amort table
			} // end for loop
		} // end else if

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

			try
			{
				loanAmt = Double.parseDouble(fieldamount.getText());
				years = Integer.parseInt(fieldyears.getText());
				interest = Double.parseDouble(fieldinterest.getText());
			}
			catch(NumberFormatException event)
			{
				JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount, Years, and Interest!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
				return; // plain old "return" since it's in actionPerformed
			}

			double paymentAmount = Calc();

			fieldPayment.setText("" + (currency.format(paymentAmount)));
			areaAmortTable.append("Payment # \t Remaining Balance \t Interest Paid\n");

			for(int x = 1; x <=(years*12); x++)
			{
				Balance=loanAmt;

				InterestPaid = (((interest/100.00)/12.0)*Balance);
				PrinciplePaid = (paymentAmount-InterestPaid);
				loanAmt = (Balance-PrinciplePaid);

				areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid) + "\n");
			}
		}
		else if ("Clear".equals(e.getActionCommand()))
		{
			ClearFields(); // action command for reset button
		}
		else if ("Quit".equals(e.getActionCommand()))
		{
			System.exit(0); // action command for quit button
		}
	}

	public double CalculatePayment7()
	{
		// check for valid numbers
		try
		{
			// perform calculations if input is valid
			fieldPayment.setText("");
			double Payment = (loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)), loanYears[0]*12));
			return Payment;
		}

		catch(NumberFormatException event)
		{
			// display error message if not numeric input
			JOptionPane.showMessageDialog(null, " Enter Numeric Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment15()
	{
		try
		{
			fieldPayment.setText("");
			double Payment=(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)), loanYears[1]*12));
			return Payment;
		}

		catch (NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, " Enter Numeric Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment30()
	{
		try
		{
			fieldPayment.setText("");
			double Payment = (loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)), loanYears[2]*12));
			return Payment;
		}
		catch (NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, "Enter Numeric Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double Calc()
	{
		try
		{
			fieldPayment.setText("");
			double Payment = (loanAmount() * (interest/100/12)) / (1 - Math.pow(1/(1 + (interest/100/12)), years*12));
			return Payment;
		}

		catch(NumberFormatException event)
		{
			JOptionPane.showMessageDialog(null, "Enter Number Value Only for Amount!", "INVALID ENTRY", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public void ClearFields()
	{
		// set all text fields to blank
		fieldPayment.setText ("");
		fieldamount.setText ("");
		areaAmortTable.setText("");
		fieldyears.setText("");
		fieldinterest.setText("");
	}

	public MortCalculation()
	{
		// set up and initialize buttons
		button7 = new JButton("7 years at 5.35%");
		button7.setActionCommand("Calculate7");
		button15 = new JButton("15 years at 5.5%");
		button15.setActionCommand("Calculate15");
		button30 = new JButton("30 years at 5.75%");
		button30.setActionCommand ("Calculate30");
		buttonCalc = new JButton("Calculate");
		buttonCalc.setActionCommand("Calc");
		buttonClear = new JButton("Reset");
		buttonClear.setActionCommand("Clear");
		buttonQuit = new JButton("Quit");
		buttonQuit.setActionCommand("Quit");

		// set up labels and text field sizes
		labelTitle = new JLabel ("Mortgage Calculator");

		labelMonthlyPay = new JLabel("Monthly Payment");
		labelAmount = new JLabel("Amount");
		fieldPayment = new JTextField("", 12);
		fieldamount = new JTextField("", 10);
		labelTerm = new JLabel("Years");
		labelRate = new JLabel("Interest Rate");
		fieldyears = new JTextField("", 12);
		fieldinterest = new JTextField("", 12);
		labelAmortTable = new JLabel("Amortization Table");
		areaAmortTable = new JTextArea(10, 300);

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

		// set up actionlisteners for each button
		button7.addActionListener(this);
		button15.addActionListener(this);
		button30.addActionListener(this);
		buttonCalc.addActionListener(this);
		buttonClear.addActionListener(this);
		buttonQuit.addActionListener(this);

		// construct gui and layout
		JPanel mypanel = new JPanel();
		mypanel.setLayout(null);

		mypanel.add(labelTitle);
		labelTitle.setBounds(150, 20, 500, 15);

		mypanel.add(labelAmount);
		labelAmount.setBounds(130, 60, 80, 25);

		mypanel.add(fieldamount);
		fieldamount.setBounds(240, 60, 100, 25);

		mypanel.add(labelTerm);
		labelTerm.setBounds(130, 85, 80, 40);

		mypanel.add(fieldyears);
		fieldyears.setBounds(240, 90, 100, 25);

		mypanel.add(labelRate);
		labelRate.setBounds(130, 125, 80, 25);

		mypanel.add(fieldinterest);
		fieldinterest.setBounds(240, 125, 100, 25);

		mypanel.add(button7);
		button7.setBounds(35, 170, 130, 30);

		mypanel.add(button15);
		button15.setBounds(180, 170, 130, 30);

		mypanel.add(button30);
		button30.setBounds(320, 170, 135, 30);

		mypanel.add(labelMonthlyPay);
		labelMonthlyPay.setBounds(130, 220, 100, 25);

		mypanel.add(fieldPayment);
		fieldPayment.setBounds(240, 220, 100, 25);
		fieldPayment.setEditable(false);

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

		// add scrollpane, set bounds and set table as not editable
		// table is part of scrollpane now, so add and place only the scrollpane
		mypanel.add(scrollPane);
		scrollPane.setBounds(50, 280, 400, 270);
		areaAmortTable.setEditable(false);

		mypanel.add(buttonCalc);
		buttonCalc.setBounds(50, 570, 100, 30);

		mypanel.add(buttonClear);
		buttonClear.setBounds(170, 570, 95, 30);

		mypanel.add(buttonQuit);
		buttonQuit.setBounds(290, 570, 95, 30);

		this.setContentPane(mypanel);
		this.pack();
		this.setTitle("Mortgage Calculator");

		// set window size
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(500, 700);
	}

	public double loanAmount()
	{
		double loanAmount = Double.parseDouble(fieldamount.getText());
		return loanAmount;
	}
}

Runs fine for me. What's the problem?

Runs fine for me. What's the problem?

I figued it out but had one more question. What I need it to do now is to clear the amort table when new information is put in. If I run it all is fine and shows the correct information in the table, but if I just add a different set of information it just adds to the table instead of clearing it.

I figued it out but had one more question. What I need it to do now is to clear the amort table when new information is put in. If I run it all is fine and shows the correct information in the table, but if I just add a different set of information it just adds to the table instead of clearing it.

areaAmortTable.setText ("") should clear it.

areaAmortTable.setText ("") should clear it.

It does clear it when you hit the reset button, but what it isn't doing is if you put the information in and it calculates and puts the information in the amort table. Unless you hit the reset button and add information in, it doesn't clear the table it just adds to it. What I want it to do is to clear the table when you just add more information in and hit calculate or if you hit one of the preset buttons. What I mean is for example if you put an amount, years, and interest in and hit calculate it gives you the output in the amort table. Then if you put a different amount, years, and interest in, it clears what is in the amort table and puts your new information in. I hope I am explaining this right.

It does clear it when you hit the reset button, but what it isn't doing is if you put the information in and it calculates and puts the information in the amort table. Unless you hit the reset button and add information in, it doesn't clear the table it just adds to it. What I want it to do is to clear the table when you just add more information in and hit calculate or if you hit one of the preset buttons. What I mean is for example if you put an amount, years, and interest in and hit calculate it gives you the output in the amort table. Then if you put a different amount, years, and interest in, it clears what is in the amort table and puts your new information in. I hope I am explaining this right.

You're explaining it fine. To clear any Text Field or Text Area, set the text for that particular TextField or TextArea to "". You do that in different spots already. So if you're calculating and it's not clearing, only appending, when you press that calculate button, have it clear the amortization Text Area before doing anything else.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.