Solved

Java calculator not providing results

Posted on 2011-09-26
7
197 Views
Last Modified: 2012-05-12
I am working on creating a mortgage calculator that calculates a monthly payment (gui).  

The code compiles, and the program runs, but when I input values and calculate, it does not provide results.  Can you see what I did wrong?

thank you.
import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$000,000.00");
	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);

	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtonCalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonReset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(LoanAmountTextField);
		centerPanel.add(interestrateLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(LoanAmountTextField.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interestrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.Calculatemonthlypayment())
	                + loan.LoanAmountRemaining());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		LoanAmountTextField.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("000,000.00");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interest;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayments = LoanTerm*12;
		return (LoanAmount * monthlyinterest) / (1.0-(Math.pow((1.0 + monthlyinterest),-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
		return Interest  / (100 * 12);
	}
	public String LoanAmountRemaining() {
		String result = "\n\n,onth\tloanbalance\tinterest paid\n";
		double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
		double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

		//setting up while loop
		while (newterminmonths > 0) {

			double loanmonths = terminmonths-newterminmonths;  //calculating the amount of months left on the term
			double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),LoanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan
			double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


		result+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
		newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
	}
		return result;
  }
}

Open in new window

0
Comment
Question by:Winstink
  • 4
  • 2
7 Comments
 
LVL 1

Expert Comment

by:webdev2000
ID: 36654118
Sorry, don't have time to check your code but try comparing your maths with this example

http://learn-java-by-example.com/2010/java/simple-mortgage-calculator
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36665740
this is almost there - bout not exactly:

import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$000,000.00");
	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);


	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtonCalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonReset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(LoanAmountTextField);
		centerPanel.add(interestrateLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(LoanAmountTextField.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interestrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.Calculatemonthlypayment())
	                + loan.LoanAmountRemaining());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		LoanAmountTextField.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
     double monPay;
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("000,000.00");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interst;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayments = LoanTerm*12;

        System.out.println("interest monthly: " + monthlyinterest);
         System.out.println("numb payments: " + numberofpayments);

        monPay =  (LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)));
        System.out.println(" amnt month: " + ((LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)))));

		return (LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
        System.out.println("Interest: " + Interest);
		return Interest  / (LoanTerm * 12*100);
	}
	public String LoanAmountRemaining() {
		String result = "\n\n,onth\tloanbalance\tinterest paid\n";
		double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
		double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

		//setting up while loop
		while (newterminmonths > 0) {

			double loanmonths = terminmonths-newterminmonths;

            //calculating the amount of months left on the term


          //  double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),LoanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan

             double loanbalance = LoanAmount - monPay*loanmonths;
            double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


		result+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
		newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
	}
		return result;
  }
}

Open in new window

0
 
LVL 2

Author Comment

by:Winstink
ID: 36667564
yeah this does help, but it is going into negative values.  
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 47

Expert Comment

by:for_yan
ID: 36682740
maybe you can use this one - it is much better and calculates everyrthing correctly:

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money




// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static String [] toReplace;
         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
       //     contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
       //     contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
        //    contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
       //     contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);


            String mortgage[] = {"Select Mortgage","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);




            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("7 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 7;
                    }
                else
                if(str.equals("15 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 15;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    monthly_payment = (principal* monthly_interest_rate)/(1 - Math.pow(1 + monthly_interest_rate, -number_of_months));
                      System.out.println("monthly interest: " + monthly_interest_rate);

                    System.out.println("monthly payment: " + monthly_payment);


                   // Sets the result text
                    result.setText("Loan Amount = " + money.format(principal)
                    +"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
                    + Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 36687699

There you go - this is your calculator after all:
import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;
import java.text.NumberFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$000,000.00");
	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);


	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtonCalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonReset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(LoanAmountTextField);
		centerPanel.add(interestrateLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(LoanAmountTextField.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interestrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.Calculatemonthlypayment())
	                + loan.LoanAmountRemaining());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		LoanAmountTextField.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
     double monPay;
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("000,000.00");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interst;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayments = LoanTerm*12;

        System.out.println("interest monthly: " + monthlyinterest);
         System.out.println("numb payments: " + numberofpayments);

        monPay =  (LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)));
        System.out.println(" amnt month: " + ((LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)))));

         System.out.println(" monPay: " + monPay);
        double loanAmount = LoanAmount;
        double monthlyRate = monthlyinterest;
        double termInMonths =  numberofpayments;

         double monthlyPayment =             (loanAmount*monthlyRate) / (1-Math.pow(1+monthlyRate, -termInMonths));
          System.out.println(" monthlyPayment: " +monthlyPayment);

		return (LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
        System.out.println("Interest: " + Interest);
		return Interest  / (12*100);
	}
    /*
	public String LoanAmountRemaining() {
		String result = "\n\n,onth\tloanbalance\tinterest paid\n";
		double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
        for(int j=0; j< LoanTerm*12; j++){
            double loanbalance = LoanAmount - monPay*j;
              double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);
            result+=(""+(j+1) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");


        }
             */





       /*
		double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

		//setting up while loop
		while (newterminmonths > 0) {

			double loanmonths = terminmonths-newterminmonths;

            //calculating the amount of months left on the term


          //  double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),LoanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan

             double loanbalance = LoanAmount - monPay*loanmonths;
            double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


		sultre+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
		newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
	}
        */
//		return result;
 // }







    public String LoanAmountRemaining() {

         String result = "\n\n,onth\tloanbalance\tinterest paid\n";
            NumberFormat nf = NumberFormat.getCurrencyInstance();
        double interest_paid;
        double principal_paid;
          double new_principal = LoanAmount;
          double principal = LoanAmount;

        for (int i = 0; i < LoanTerm*12; i++) {
                      Object data[] = new Object[6];
                       data[0] = Integer.toString(i + 1);
                      data[1] = nf.format(new_principal);
                      data[2] = nf.format(monPay);
                      data[3] = nf.format(interest_paid = principal * Calculatemonthlyinterest(Interest));
                      data[4] = nf.format(principal_paid = monPay - interest_paid);
                      data[5] = nf.format(principal = principal - principal_paid);
                      new_principal = principal;
            result += "" + (i+1) + "\t" +   Dollar.format(new_principal) + "\t" + Dollar.format(interest_paid) + "\n";
              System.out.println(data[5]);
        }




     /*
        String result = "\n\n,onth\tloanbalance\tinterest paid\n";


        double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
        double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

        //setting up while loop
        while (newterminmonths > 0) {

            double loanmonths = terminmonths-newterminmonths;  //calculating the amount of months left on the term
            double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),LoanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan
            double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


        result+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
        newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
    }
        */
        return result;
  }

}

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 36694113

cleaned up a little bit

import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;
import java.text.NumberFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$###,###.##");

	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);


	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtonCalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonReset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(LoanAmountTextField);
		centerPanel.add(interestrateLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(LoanAmountTextField.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interestrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.Calculatemonthlypayment())
	                + loan.LoanAmountRemaining());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		LoanAmountTextField.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
     double monPay;
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("0,000.00");
     DecimalFormat Dollar1 = new DecimalFormat("$#,###.##");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interst;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayments = LoanTerm*12;

       // System.out.println("interest monthly: " + monthlyinterest);
        // System.out.println("numb payments: " + numberofpayments);

        monPay =  (LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)));
     //   System.out.println(" amnt month: " + ((LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)))));

       //  System.out.println(" monPay: " + monPay);
        double loanAmount = LoanAmount;
        double monthlyRate = monthlyinterest;
        double termInMonths =  numberofpayments;

         double monthlyPayment =             (loanAmount*monthlyRate) / (1-Math.pow(1+monthlyRate, -termInMonths));
         // System.out.println(" monthlyPayment: " +monthlyPayment);

		return (LoanAmount * monthlyinterest) / (1.0-(Math.pow(1.0 + monthlyinterest,-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
       // System.out.println("Interest: " + Interest);
		return Interest  / (12*100);
	}
   






    public String LoanAmountRemaining() {

         String result = "\n\n,onth\tloanbalance\tinterest paid\n";
            NumberFormat nf = NumberFormat.getCurrencyInstance();
        double interest_paid;
        double principal_paid;
          double new_principal = LoanAmount;
          double principal = LoanAmount;

        for (int i = 0; i < LoanTerm*12; i++) {
                      Object data[] = new Object[6];
                       data[0] = Integer.toString(i + 1);
                      data[1] = nf.format(new_principal);
                      data[2] = nf.format(monPay);
                      data[3] = nf.format(interest_paid = principal * Calculatemonthlyinterest(Interest));
                      data[4] = nf.format(principal_paid = monPay - interest_paid);
                      data[5] = nf.format(principal = principal - principal_paid);
                      new_principal = principal;
            result += "" + (i+1) + "\t" +   Dollar.format(new_principal) + "\t" + Dollar1.format(interest_paid) + "\n";
             // System.out.println(data[5]);
        }





        return result;
  }

}

Open in new window

0
 
LVL 2

Author Closing Comment

by:Winstink
ID: 36709592
thank you
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now