• 0

[Java] Need help with error catching and calculations


Question

I've been working on this code for a few days and almost everything is working. It's a different version of the one which I psted several weeks ago as this one includes a GUI.

I have two problems with the code which I need to iron out:

First problem is that for CalculateX, it does not show an error pop-up window when I enter letters for either Rate or Term. The error only pops up for a letter in the loan amount box.

Problem number two is that CalculateX (the Calculate button at the bottom) does not seem to give me correct results. If I enter the numbers for 30 years and 5.75 interest rate (as in button number 3 along the top) I get the correct results. However, when I try to replicate the results of buttons 1 or 2 from above I don't get correct results.

Any help would be greatly appreciated!!

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


public class MortgageCalculator
{
	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
	protected JButton bCalc1, bCalc2, bCalc3, bCalc4, bClear, bExit;
	protected JLabel labelPayment, labelLoanAmount, labelTitle, labelInstructions, labelAmortTable, labelTerm, labelRate;
	protected JTextField fieldPayment, fieldLoanAmount, fieldRate, fieldTerm;
	protected JTextArea areaAmortTable;


	// Declare variables and loan array and initialize with values
	double InterestPaid, PrinciplePaid, Balance, monthlyPay, loanAmount;
	int [] loanTerm = {7, 15, 30};
	double [] intRate = {5.35, 5.50, 5.75};
	double loanAmt = loanAmount;


	public void actionPerformed (ActionEvent e)
	{
		// Perform calculations based on which button is 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 the loan amount to the value from the field first
			loanAmt = Double.parseDouble(fieldLoanAmount.getText());

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

					Balance=loanAmt;

					// Calculations on monthly payment
					InterestPaid = (((intRate[0]/100.0)/12.0)*Balance); // Monthly Interest paid
					PrinciplePaid = (paymentAmount - InterestPaid); // Payment 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)
			{
				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());

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

					Balance = loanAmt;

					// Calculations on 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");
			}

			if (loanAmt <= 0)
			{
				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());


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

				// Calculations on 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");
			}

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

			}

		}

		else if ("CalculateX".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());
					double rate = Double.parseDouble(fieldRate.getText());
					double term = Double.parseDouble(fieldTerm.getText());


					// Loop through monthly payments
					for (int x = 1; x <=(term*12); x++)
					{
						Balance = loanAmt;

						// Calculations on monthly payment
						InterestPaid = ((rate/100/12)*Balance);
						PrinciplePaid = (paymentAmount - InterestPaid);
						loanAmt = ((Balance - PrinciplePaid));

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

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

			}

		}

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

		else
		{
			System.exit(0);
	   }
	}

	public double CalculatePayment7 ()
	{

		// Check for valid numeric input
		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 for invalid inputs
			JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePayment15 ()
	{
		// Check for valid numeric input
		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 for invalid inputs
			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 for invalid inputs
			JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
			return 0;
		}
	}

	public double CalculatePaymentX ()
		{
			// Check for valid numeric imput
			try
			{
				// Perform payment calculations if input is valid
				fieldPayment.setText ("");
				double rate = Double.parseDouble(fieldRate.getText());
				double term = Double.parseDouble(fieldTerm.getText());
				double Payment = (loanAmount() * (rate/100/12)) / (1 - Math.pow(1/(1 + (rate/100/12)),term*12));
				return Payment;
			}

			catch (NumberFormatException event)
			{
				//Display error message for invalid inputs
				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 ("");
		fieldRate.setText ("");
		fieldTerm.setText ("");
		areaAmortTable.setText ("");
	}

	public MortCalcGUI ()
	{
		// Set up and initialize GUI buttons
		bCalc1 = new JButton ("7 Year/5.35%");
		bCalc1.setActionCommand ("Calculate7");
		bCalc2 = new JButton ("15 Year/5.50%");
		bCalc2.setActionCommand ("Calculate15");
		bCalc3 = new JButton ("30 Year/5.75%");
		bCalc3.setActionCommand ("Calculate30");
		bCalc4 = new JButton ("Calculate");
		bCalc4.setActionCommand ("CalculateX");
		bClear = new JButton ("Clear All Fields");
		bClear.setActionCommand ("Clear");
		bExit = new JButton ("Exit Program");
		bExit.setActionCommand ("Exit");

		// Set up GUI labels and field sizes
		labelTitle = new JLabel ("Mortgage Calculator for McBride Financial");
		labelInstructions = new JLabel ("Enter the amount of the loan and then choose the term/rate of the loan.");

		labelPayment = new JLabel ("Monthly Payment:");
		labelLoanAmount = new JLabel ("Amount of loan:");
		labelRate = new JLabel ("Interest rate:");
		labelTerm = new JLabel ("Term of loan:");
		fieldPayment = new JTextField ("", 12);
		fieldLoanAmount = new JTextField ("", 10);
		fieldRate = new JTextField ("", 10);
		fieldTerm = new JTextField ("", 10);
		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 listeners for each button
		bCalc1.addActionListener(this);
		bCalc2.addActionListener(this);
		bCalc3.addActionListener(this);
		bCalc4.addActionListener(this);
		bClear.addActionListener(this);
		bExit.addActionListener(this);

		// Build 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 (40, 70, 450, 15);

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

		mine.add (fieldLoanAmount);
		fieldLoanAmount.setBounds (40, 140, 100, 25);

		mine.add (labelTerm);
		labelTerm.setBounds (180, 110, 125, 25);

		mine.add (fieldTerm);
		fieldTerm.setBounds (180, 140, 100, 25);

		mine.add (labelRate);
		labelRate.setBounds (320, 110, 125, 25);

		mine.add (fieldRate);
		fieldRate.setBounds (320, 140, 100, 25);

		mine.add (bCalc1);
		bCalc1.setBounds (40, 190, 125, 30);

		mine.add (bCalc2);
		bCalc2.setBounds (180, 190, 125, 30);

		mine.add (bCalc3);
		bCalc3.setBounds (320, 190, 125, 30);

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

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

		mine.add (labelAmortTable);
		labelAmortTable.setBounds (190, 295, 300, 25);


		// Add the scrollpane, set its bounds and set the table as not editable
		mine.add (scrollPane);
		scrollPane.setBounds (40, 320, 405, 270);
		areaAmortTable.setEditable(false);

		mine.add (bCalc4);
		bCalc4.setBounds (40, 610, 125, 30);

		mine.add (bClear);
		bClear.setBounds (180, 610, 125, 30);

		mine.add (bExit);
		bExit.setBounds (320, 610, 125, 30);

		this.setContentPane(mine);
		this.pack();
		this.setTitle("Mortgage Amortization Calculator");

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

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.