Java Mortgage calculator else if not working

else if issues I can not get it to work. Ideas???

Page 1 of 1

1 Replies - 2774 Views - Last Post: 17 July 2009 - 07:02 PM Rate Topic: -----

#1 C-Rookie   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 15-December 07

Java Mortgage calculator else if not working

Post icon  Posted 17 July 2009 - 04:16 PM

	Program: Mortgage Calculator with Graphical User Interface
		Current Version: 2.0
		Programs accepts user input in 3 text fields: Term, Amount, and Rate.
			When any field changes, Monthly Payment (output) updates.
		Used Formatted Text Fields to prevent character input.
			  2.0 01/11/2007
			   Program accepts user input for the mortgage amount. Payment amount
			   is calculated from a radio button selection of the following:
			 7 year loan at 5.35%
			15 year loan at 5.50%
			30 year loan at 5.75%
		User can also select to see an amortization table for each of the
				loan choices (stored in an array)


   import java.awt.*;  //Abstract Windows Toolkit
   import java.awt.event.*; //Action Listener
   import javax.swing.*;//Swing Container
   import javax.swing.JScrollPane;
   import javax.swing.JFrame;
   import javax.swing.JPanel;
   import javax.swing.JTable;
   import java.beans.PropertyChangeListener; //allows the program to listen to property changes from any bound properties on the source bean
   import java.beans.PropertyChangeEvent;
   import java.text.*;//Provides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages
   import java.text.DecimalFormat;
   import javax.swing.JMenu;
   import javax.swing.JMenuItem;
   import javax.swing.JMenuBar; //imports for the menu system
   import javax.swing.KeyStroke;

	public class MortgageGUI extends JPanel implements PropertyChangeListener, ActionListener
   {	//Variable declaration here so they are accessible to all methods
   //declare fields for user input and program output
	  private static JFrame frame = new JFrame("Monthly Mortgage Calculator");
	  private JFrame tableFrame = new JFrame("Amortization Table");
	  private JTable table; //used to hold the amortization table
	  private JFormattedTextField loanAmountField;  
	  private JFormattedTextField paymentAmountField;
   //set to default values for before user input has occurred
	  private static double interestRate; //value changed for v2.0
	  private static double loanAmount;
	  private static int term;//value changed for v2.0
   //declare a JLabel for 4 objects in the program
	  private JLabel loanAmountLabel;
	  private JLabel paymentAmountLabel;
	  private JLabel selectionLabel;
   //declare a button used for displaying the amortization table
	  private static JButton tableButton;
   //Formats for each field for proper output
	  private NumberFormat loanAmountFormat;
	  private NumberFormat paymentAmountFormat;
	  private static JMenuBar mortgageMenuBar;
	  private static JMenu frameMenu;
	  private static JMenuItem helpItem, aboutItem;
   //selections for the loan types
	  private static String [] loanChoicesStr = {"7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};
	  private static JComboBox loanChoicesBox = new JComboBox(loanChoicesStr);
	  private static JScrollPane scrollPane;
	  private static JComponent tablePane;
   //begin methods
	   public MortgageGUI() //contrustor for the class
		 super(new BorderLayout(5,2)); //calls the superclass constructor and uses a layout with horizontal spacing of 4 and vertical spacing of 2
		 //setup menu
		 mortgageMenuBar = new JMenuBar();
		 //Build the menu.
		 frameMenu = new JMenu("Help");
		 frameMenu.getAccessibleContext().setAccessibleDescription("Mortgage GUI help menu");
		 helpItem = new JMenuItem("Instructions", KeyEvent.VK_I);
		 helpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.ALT_MASK));
		 helpItem.getAccessibleContext().setAccessibleDescription("Displays instructions for using the Mortgage Calculator");
		 aboutItem = new JMenuItem("About", KeyEvent.VK_A);
		 aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK));
		 aboutItem.getAccessibleContext().setAccessibleDescription("Displays information about the Mortgage Calculator");
	  //initialize formats
		 loanAmountFormat = NumberFormat.getNumberInstance(); //gets the local format for numbers
		 paymentAmountFormat = NumberFormat.getCurrencyInstance(); //gets the local currency format
	  //set default values
	  //calculate the payment Amount
		 double paymentAmount = calculatePayment(loanAmount, interestRate, term);
	  //Creates labels for objects
		 paymentAmountLabel = new JLabel("Monthly Payment");
		 loanAmountLabel = new JLabel("Loan Amount");
		 selectionLabel = new JLabel("Loan Choices");
	  //Create the text fields and sets them up.
		 loanAmountField = new JFormattedTextField(loanAmountFormat);
		 loanAmountField.setValue(new Double(loanAmount));
		 loanAmountField.addPropertyChangeListener("value", this);
		 paymentAmountField = new JFormattedTextField(paymentAmountFormat);
		 paymentAmountField.setValue(new Double(paymentAmount));
		 paymentAmountField.setEditable(false); //the output field should not be editable
	  //pairs the labels with the fields
	  //create a combobox for the loan choices
	  //create a new Jpanel and add the labels
		 JPanel labelPane = new JPanel(new GridLayout(4,1)); //uses a grid layout with 1 column, and 4 rows
	  //create a new Jpanel and add the fields
		 JPanel fieldPane = new JPanel(new GridLayout(4,1)); //uses a grid layout with 1 column and 4 rows
	  //create a help pane
		 JPanel tablePane = new JPanel();
		 tableButton = new JButton("Show Current Amortization Table");
	  //puts the three panels in the main panel
		 setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
		 add(labelPane, BorderLayout.WEST);
		 add(fieldPane, BorderLayout.CENTER);
		 add(tablePane, BorderLayout.SOUTH);
	   public MortgageGUI(int value) //constructor for setting up amortization table frame
		 super(new BorderLayout(5,2));
		 int size = value * 12;
		 String[] columnNames = {"Payment #","Balance","Interest Paid"};
		 Object[][] data = new Object[size][3];
		 DecimalFormat moneyFormat = new DecimalFormat("$###,###,##0.00");
		 NumberFormat paymentNumberFormat = NumberFormat.getIntegerInstance();;
		 JPanel infoPane = new JPanel();
		 String infoStr = "Table shown for a " + moneyFormat.format(loanAmount) + " loan for " + term + " years at %" + interestRate;
		 JLabel infoLabel = new JLabel(infoStr);
	  //calculate values and get arrays ready for declaring the table
		 double monthlyPaymentAmount = calculatePayment(loanAmount, interestRate, term);
		 double currentPrinciple = loanAmount; //keeps track of the current principle remaining
		 double monthlyInterestRate = (interestRate/100/12); //used for storing how much interest is paid each month
		 double monthlyInterest = 0;
		 double totalInterest = 0; //keeps track of interest paid  
		 int numberOfPayments = 1; //used as a counter in the while loop
		 monthlyInterest = currentPrinciple * monthlyInterestRate;
		 data[0][2]=new String(moneyFormat.format(monthlyInterest));
		 currentPrinciple -= (monthlyPaymentAmount-monthlyInterest);
		 totalInterest += monthlyInterest;
		 data[0][1]=new String(moneyFormat.format(currentPrinciple));		 
		 data[0][0]=new String(paymentNumberFormat.format(numberOfPayments));
		 while(numberOfPayments(0.0)); //check to make sure it's positive
			   loanAmount = ((Number)loanAmountField.getValue()).doubleValue(); 
			   	//if positive update the loan amount variable
		   else if(loanAmount-=0)	//negative, so output an error message and update loan amount to default value
			   JOptionPane.showMessageDialog(frame, "Please Enter only positive non-zero values.", "Input error", JOptionPane.ERROR_MESSAGE); 
			   loanAmount = 200000;
			   loanAmountField.setValue(new Double(loanAmount));
		 double paymentAmount = calculatePayment(loanAmount, interestRate, term); //redo the monthly payment calc
		 paymentAmountField.setValue(new Double(paymentAmount));	//update the field
	   public void actionPerformed(ActionEvent currentSelection) 
		 Object source = (Object)currentSelection.getSource(); //determine which object caused the event
		 if(source == tableButton)
		 //Create and set up the content pane.
		 JComponent amortizationTablePane = new MortgageGUI(term);
		 amortizationTablePane.setOpaque(true); //content panes must be opaque
		 tableFrame.pack(); //sets the size of the window to fit all of the objects in it
		 else if(source==loanChoicesBox)
			JComboBox src = (JComboBox)currentSelection.getSource();
			String loanChoice = (String)src.getSelectedItem();// place the choice label into the string currentBox
			if(loanChoice == "7 years at 5.35%")
			   interestRate = 5.35;
			   term = 7;	 
			else if(loanChoice == "15 years at 5.5%")
			   interestRate = 5.5;
			   term = 15;
			else if(loanChoice == "30 years at 5.75%")
			   interestRate = 5.75;
			   term = 30;
		 else if(source==helpItem)
			   JOptionPane.showMessageDialog(frame, "Update the loan amount field\nand press enter to update.\nSelecting a new loan choice will\nAutomatically update the payment amount.");
		 else if(source==aboutItem)
			   JOptionPane.showMessageDialog(frame, "Mortgage Calculator Version 2.0\nAuthor: Ericson Wilkinson\nJanuary 12, 2007");
		 double paymentAmount = calculatePayment(loanAmount, interestRate, term); //redo the monthly payment calc
		 paymentAmountField.setValue(new Double(paymentAmount)); //update the field
	   private static void setupGUI()
		 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //allows the program to exit when the X button is clicked
		 JComponent mainContentPane = new MortgageGUI();
		 mainContentPane.setOpaque(true); //content panes must be opaque
		 frame.pack(); //sets the size of the window to fit all of the objects in it
	   //setup the amortization table frame
	   //make it scrollable and show scroll bars
	   public static void main(String[] args) 
	  {//the following code is from is used for thread safety  
		 javax.swing.SwingUtilities.invokeLater(new Runnable(){public void run(){setupGUI();}}); //end code from (open source)
   //returns the monthly payment amount
	   double calculatePayment(double loanAmount, double interestRate, int term) 
		 return(loanAmount * (interestRate/1200)/(1-java.lang.Math.pow(1+(interestRate/1200), -(term*12))));

Is This A Good Question/Topic? 0
  • +

Replies To: Java Mortgage calculator else if not working

#2 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Java Mortgage calculator else if not working

Posted 17 July 2009 - 07:02 PM

syntax for an if else statement is

if(condition1) {
else if(condition2) {


if(condition) {
else {

here you else is not associated with any if

			   loanAmount = ((Number)loanAmountField.getValue()).doubleValue(); 
				   //if positive update the loan amount variable
		   else if(loanAmount-=0)	//

also this while looks ackward to me (it can be right if numberOfPayments(0,0) returns a boolean

  while(numberOfPayments(0.0)); //check to make sure it's positive

but will simply loop on itself because of the ;

syntax is:


you are doing
while(condition);	<--- note the; here

so the only statement executed in the while is numberOfPayments(0,0) NOT the statement following the ;
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1