Solved

Mortgage calculator sometimes displays -0.00

Posted on 2006-06-14
2
277 Views
Last Modified: 2012-05-05
Hi,
My mortgage calculato seems to me to be working well with one issue. When I use 200000 as the amount and select the first loan radio button, the last payment displays -0.00 rather than 0.00. It does not do this with the same 200000 for the other loans. I don't really want to check the tesxt field for the negative aqnd assign te positive value. Is there a way for me to dictate the value should always be positive?
Any assistance appreciated.
Thanks,
Jon
//Week3 Jan Schab


/* Mortgage Monyhly Payment Calculator with graphical user interface
Programmer:  J.Schab
Date:        June 10,2006
Filename:    Mortgage.java
Purpose:     This project accepts the mortgage amountand allows  the user to select one of 3
pre-determined loans.The program then calculates the monthly mortgage payment and displays
it in currency format. The program then displays the payment number, the monthly principle
paid, the monthly interest paid, and the current loan balance.There is a quit button to
exit the application, and a clear button to clear user entered fields in order to calculate
a new mortgage. The program will also clear the payment field should the user press any key
while positioned in the input textfield for amount.


 */



import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JScrollPane.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.*;
import java.text.DecimalFormat;



class Mortgage extends JFrame
{


    //Program variables

    double yearlyRate[] =
    {
        // array of interest rates
        5.35, 5.50, 5.75
    };
    int term[] =
    {
        //array of terms
        7, 15, 30
    };
    int termMonths[] =
    {
        //array of terms in months
        84, 180, 360
    };

    int i = 0;

    double loanbalance = 0.00;
    double monthlyPrinciplePaid = 0.00;
    double monthlyInterest = 0.00;
    double loanBalance = 0.00;
    int payment = 0; // payment counter


    private JLabel headerJLabel;

    Border rowborder = new EmptyBorder(3, 10, 3, 10);


    // JLabel and JTextField for the mortgage amount
    private JLabel amountJLabel;
    private JTextField amountJTextField;

    // JLabel for monthly mortgage payment
    private JLabel monthpayJLabel;

    // JTextArea for displaying payment
    private JTextArea outputJTextArea;


    // JButton to initiate calculations
    private JButton calculateJButton;

    // JButton to clear entries
    private JButton clearJButton;

    // JButton to quit
    private JButton quitJButton;

    JPanel radioPanel = new JPanel();
    JRadioButton aButton = new JRadioButton("7 Years at 5.35%", true);
    JRadioButton bButton = new JRadioButton("15 Years at 5.50%", false);
    JRadioButton cButton = new JRadioButton("30 Years at 5.75%", false);

    JTextArea displayArea = new JTextArea(10, 45);
    JScrollPane scroll = new JScrollPane(displayArea);




    // no-argument constructor
    public Mortgage()



    {
        createUserInterface();
    }

    // create and position the GUI components; register event handlers
    private void createUserInterface()
    {
        // get content pane for attaching GUI components
        Container contentPane = getContentPane();

        setTitle("Mortgage Calculator"); // set title bar text


        // set northLabel using borderlayout
        headerJLabel = new JLabel();
        headerJLabel.setBounds(10, 1, 300, 46);
        headerJLabel.setText("Enter a mortgage amount and select a loan");
        contentPane.add(headerJLabel);

        // enable specific positioning of GUI components
        contentPane.setLayout(null);

        // set up amountJLabel
        amountJLabel = new JLabel();
        amountJLabel.setBounds(76, 36, 104, 26);
        amountJLabel.setText("Mortgage amount:");
        contentPane.add(amountJLabel);

        // set up amountJTextField
        amountJTextField = new JTextField();
        amountJTextField.setBounds(200, 36, 56, 26);
        amountJTextField.setHorizontalAlignment(JTextField.RIGHT);
        contentPane.add(amountJTextField);
        amountJTextField.addKeyListener(

        new KeyAdapter() // anonymous inner class
        {
            // event handler for key pressed in amountJTextField
            public void keyPressed(KeyEvent event)
            {
                amountJTextFieldkeyPressed(event);
            }

        } // end anonymous inner class

        ); // end call to addKeyListener


        ButtonGroup bgroup = new ButtonGroup();
        bgroup.add(aButton);
        bgroup.add(bButton);
        bgroup.add(cButton);
        radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
        radioPanel.add(aButton);
        radioPanel.add(bButton);
        radioPanel.add(cButton);
        contentPane.add(radioPanel);
        //radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height ) );
        radioPanel.setBorder(rowborder);
        radioPanel.setBounds(90, 56, 195, 95);



        // set up calculateJButton
        calculateJButton = new JButton();
        calculateJButton.setBounds(26, 320, 90, 26);
        calculateJButton.setText("Calculate");
        contentPane.add(calculateJButton);
        calculateJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when calculateJButton is pressed
            public void actionPerformed(ActionEvent event)
            {

                calculateJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up clearJButton
        clearJButton = new JButton();
        clearJButton.setBounds(136, 320, 90, 26);
        clearJButton.setText("Clear");
        contentPane.add(clearJButton);
        clearJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when clearJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                clearJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up quitJButton
        quitJButton = new JButton();
        quitJButton.setBounds(250, 320, 90, 26);
        quitJButton.setText("Quit");
        contentPane.add(quitJButton);
        quitJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when quitJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                quitJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up outputJTextArea
        outputJTextArea = new JTextArea();
        contentPane.add(outputJTextArea);
        outputJTextArea.setBounds(200, 146, 56, 26);
        outputJTextArea.setEditable(false);

        //set up monthpayJLabel
        monthpayJLabel = new JLabel();
        monthpayJLabel.setBounds(76, 146, 156, 26);
        monthpayJLabel.setText("Monthly Payment:");
        contentPane.add(monthpayJLabel);

        scroll.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        contentPane.add(scroll);
        scroll.setBounds(20, 186, 356, 130);
        setVisible(true);





    } // end method createUserInterface

    // called when user presses key in amountJTextField
    private void amountJTextFieldkeyPressed(KeyEvent event)
    {
        outputJTextArea.setText(""); // clear outputJTextArea
        displayArea.setText(""); // clear DISPLAY AREA
        payment = 0;
    }

    // method called when user clicks calculateJButton
    private void calculateJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            if (aButton.isSelected())
            {
                i = 0;
            }


            if (bButton.isSelected())
            {
                i = 1;
            }


            if (cButton.isSelected())
            {
                i = 2;
            }



            payment = 0;
            outputJTextArea.setText(""); // clear outputJTextArea
            displayArea.setText(""); // clear DISPLAY AREA
            String titles = "Month \t Principal\t Interest\tBalance\n";
            displayArea.setText(titles);
            int monthCount = (term[i] * 12); // Calculate months from years
            int amount = Integer.parseInt(amountJTextField.getText());
            double principle = amount;
            double interestRateMonthly = (yearlyRate[i] / 12) / 100;
            // Calculate monthly interest
            double monthlyPayment; // monthly payment amount variable

            // Calculate monthly payment
            monthlyPayment = (amount * interestRateMonthly) / (1-Math.pow(1
                +interestRateMonthly,  - monthCount));



            DecimalFormat currency = new DecimalFormat("$0.00");
            // Format output
            outputJTextArea.setText(currency.format(monthlyPayment));
            // Output payment amount

            for (int a = 0; a < termMonths[i]; a = a + 1)
            {
                payment++; //increment payment counter
                monthlyInterest = principle * interestRateMonthly;
                monthlyPrinciplePaid = monthlyPayment - monthlyInterest;
                principle = principle - monthlyPrinciplePaid;


                displayArea.append(payment + "\t" + currency.format
                    (monthlyPrinciplePaid) + "\t" + currency.format
                    (monthlyInterest) + "\t" + currency.format(principle) +
                    "\n");
                displayArea.setCaretPosition(0);


            }
        }

        catch (NumberFormatException ex){}
    }





    // method called when user clicks clearJButton
    private void clearJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            outputJTextArea.setText(""); // clear outputJTextArea
            amountJTextField.setText(""); // clear amountJTextField
            displayArea.setText(""); // clear DISPLAY AREA
            payment = 0; // payment counter




        }
        catch (NumberFormatException ex){}
    }





    // method called when user clicks quitJButton
    private void quitJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            System.exit(0);

        }
        catch (NumberFormatException ex){}
    }



    // main method
    public static void main(String[]args)
    {
        Mortgage application = new Mortgage();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.setSize(400, 400);
        application.setVisible(true);
    } // end method main

} // end class Mortgage

0
Comment
Question by:ghost8067
2 Comments
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 16907543
try:

currency.format(Math.abs(principle))
0
 

Author Comment

by:ghost8067
ID: 16907797
Many thanks. Works like a charm.
Jon
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

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…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

860 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