473,769 Members | 2,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Java GUI Mortgage Program, Output Incorrect

59 New Member
I have finally gotten my GUI to look like I want it to, but I am having trouble getting the calculations right. No matter what I put in there, it seems to calculate a large payment, and a very wrong amortization schedule... Here is what I have so far...


Expand|Select|Wrap|Line Numbers
  1. package guiweek3;
  2.  
  3. //imports necessary tools
  4. import java.io.*;
  5. import java.awt.*;
  6. import javax.swing.*;
  7. import java.awt.event.*;
  8. import javax.swing.border.*;
  9. import javax.swing.text.*;
  10. import java.text.*;
  11. import java.util.*;
  12.  
  13. //creates the different fields, labels for the fields, and the panel and buttons
  14. public class guiweek3 extends JFrame implements ActionListener 
  15. {
  16.     //creates gui panel and compnents including text fields and labels
  17.     private JPanel panelTop = new JPanel(new GridLayout (3,3));
  18.     private JPanel panelMid = new JPanel(new FlowLayout());
  19.     private JPanel panelBottom = new JPanel();
  20.     private JTextField amountField = new JTextField();
  21.     private JTextField paymentField = new JTextField();
  22.     private JLabel paymentLabel = new JLabel("Monthly Payment:");
  23.     private JLabel amountLabel = new JLabel("Enter Your Loan Amount: $");
  24.     private JLabel loanLabel = new JLabel("Choose Your Loan Terms:");
  25.     private JComboBox loanMenu = new JComboBox();
  26.     private JTextArea amortizationSchedule = new JTextArea(25,50);
  27.     private JButton calculateButton = new JButton("Calculate Payment");
  28.     private JButton clearButton = new JButton("Clear Fields");
  29.     private JButton quitButton = new JButton("Quit");
  30.     static DecimalFormat usDollar = new DecimalFormat("$###,##0.00");
  31.  
  32.     //create arrays for the three loans
  33.     int[] yearsArray = {7, 15, 30};
  34.     double[] interestArray = {5.35, 5.50, 5.75};
  35.  
  36.     //exit action
  37.     public guiweek3() 
  38.     {
  39.         initComponents();
  40.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  41.         setVisible(true);
  42.         pack();
  43.  
  44.         //adds the listen action to the calculate, clear, and quit buttons
  45.         calculateButton.addActionListener(this);
  46.         quitButton.addActionListener(this); 
  47.         clearButton.addActionListener(this);
  48.     }
  49.  
  50.     //adds the individual components (panel, fields, labels, buttons)to the 
  51.     //panel, sets column sizes for the text fields. Makes payment field static.
  52.     public void initComponents() 
  53.     {
  54.         //creates the object attributes
  55.         amountField.setColumns(8);
  56.         paymentField.setColumns(8);
  57.         paymentField.setEditable(false);
  58.  
  59.         Container pane = getContentPane();
  60.         pane.setLayout(new FlowLayout());
  61.         JScrollPane amortizationPanel = new JScrollPane(amortizationSchedule);
  62.         amortizationSchedule.setEditable(false);
  63.  
  64.         //creates the components and adds them to the panel
  65.         panelTop.add(amountLabel);
  66.         panelTop.add(amountField);
  67.         panelTop.add(loanLabel);
  68.         panelTop.add(loanMenu);
  69.         panelTop.add(paymentLabel);
  70.         panelTop.add(paymentField);
  71.         panelMid.add(calculateButton);  
  72.         panelMid.add(clearButton);
  73.         panelMid.add(quitButton); 
  74.         panelBottom.add(amortizationPanel);
  75.         pane.add(panelTop);
  76.         pane.add(panelMid);
  77.         pane.add(panelBottom);
  78.  
  79.         for(int i=0; i<3; i++)
  80.         {
  81.             loanMenu.addItem(interestArray[i] + "% interest for " + yearsArray[i] + " years");
  82.         } //end for     
  83.     }//end initComponents
  84.  
  85.     //creates frame called guiweek2
  86.     public static void main(String[] args) throws IOException
  87.     {
  88.         guiweek3 frame = new guiweek3();
  89.         frame.setTitle("Calculator Your New Mortgage Payment");
  90.         frame.setBounds(200, 200, 600, 600);
  91.     }//end main
  92.  
  93.     //if the calculate button is pressed, set the amount
  94.     public void actionPerformed(ActionEvent event) 
  95.     {       
  96.         if (event.getSource() == calculateButton) 
  97.         {       
  98.             //error handling try/catch, and cases for the different loans avaialble
  99.             try
  100.             {
  101.                 double term;
  102.                 double rate; 
  103.  
  104.                 switch (loanMenu.getSelectedIndex())
  105.                 {
  106.                     case 0:
  107.                     rate = interestArray[0];
  108.                     term = yearsArray[0];
  109.                     break;
  110.  
  111.                     case 1:
  112.                     rate = interestArray[1];
  113.                     term = yearsArray[1];
  114.                     break;
  115.  
  116.                     case 2:
  117.                     rate = interestArray[2];
  118.                     term = yearsArray[2];
  119.                     break;
  120.                 }//end switch       
  121.  
  122.                 double amount = Double.parseDouble (amountField.getText());                        
  123.  
  124.                 //formatting for currencies and percentages
  125.                 NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);                      
  126.  
  127.                 for (int i = 0; i<3; ++i)
  128.                 {                                        
  129.                     double monthlyInterest = interestArray[i] / 12;
  130.                     double months = yearsArray[i] * 12;            
  131.                     double payment = (amount * monthlyInterest) / (1 - Math.pow((1 + monthlyInterest), months * -1));                   
  132.                     double remainingPrincipal = (amount - payment);
  133.  
  134.                     paymentField.setText(usDollar.format(payment));                                                      
  135.  
  136.                     //calculations for amortization results
  137.                     while (remainingPrincipal > 0)     
  138.                     {
  139.                         double interestPayment = (remainingPrincipal * (interestArray[i] / 1200) * 1);                          
  140.  
  141.                         //Display loan balance and interest paid
  142.                         amortizationSchedule.append ("Balance:" + usDollar.format(remainingPrincipal) 
  143.                         + "\tInterest Paid:" + usFormat.format(interestPayment) +"\n");
  144.  
  145.                         // Subtract amount paid to principal from loan balance
  146.                         remainingPrincipal = remainingPrincipal - payment;
  147.                     }//end while
  148.                 }//end for
  149.             }//end try
  150.  
  151.             //error message to user if loan is not entered as a number
  152.             catch(NumberFormatException i)
  153.             {
  154.                 JOptionPane.showMessageDialog(null, "You must enter the loan " +
  155.                         "amount as a number.", "Invalid Entry", JOptionPane.INFORMATION_MESSAGE);
  156.             }//end catch
  157.         }//end if calculate
  158.  
  159.         //if the clear button is pressed, clear the fields
  160.         if (event.getSource() == clearButton) 
  161.         {
  162.             amountField.setText("");
  163.             paymentField.setText("");
  164.             amortizationSchedule.setText("");
  165.         }//end if clear statement
  166.  
  167.         //if the quit button is pressed, exit the application
  168.         if (event.getSource() == quitButton) 
  169.         {
  170.             System.exit(0);
  171.         }//end if quit statement
  172.     }//end actionPerformed
  173. }//end class guiweek3
Mar 2 '08 #1
3 3618
sukatoa
539 Contributor
Please assume an input and also the expected output,

Sukatoa,
Mar 2 '08 #2
zaidalin79
59 New Member
Please assume an input and also the expected output,

Sukatoa,
The user could put in 200000 as the loan amount. The program should display the monthly payment amount based on the loan they chose from the drop down, and then display the amortization schedule in nthe larger text area; showing the remaining balance and payment to interest for each payment through the life of the loan. I am able to do what I need without the gui, but when I try to move over my code and calculations, I cannot seem to get it right....

Please help!!

Thanks!!
Mar 2 '08 #3
sukatoa
539 Contributor
The user could put in 200000 as the loan amount. The program should display the monthly payment amount based on the loan they chose from the drop down, and then display the amortization schedule in nthe larger text area; showing the remaining balance and payment to interest for each payment through the life of the loan. I am able to do what I need without the gui, but when I try to move over my code and calculations, I cannot seem to get it right....

Please help!!

Thanks!!
I would like to help you... but it needs time to analyze if you just show the input and without the expected output... And also without the formula...

I have no experience in accounting...


If you assume that the loan amount is 200000,

and the loan terms is 5.35% interest for 7 years ( if i am right, total interests for 7 years to pay...)

And im going to pay it in installment for 7 years,

5.35% of 200000 is 10700 right?

The total payment i must pay before or in 7 years is 210700? am i right?

84 months in 7 years right?

210700 divide by 84 months is 2508.33 right?

That is the monthly payment i should pay...


If the assumptions above is correct, then maybe there is something you must fix in the calculations...
At your program,

i assume 200000 in loan amount,
Monthly payments is 93.8 thousand dollars...

It should be 2508.33 dollars per month...

At the textArea, it is confusing,

Why you put the balance first before the interest paid?
Is that mean that when i pay 494.13, my new balance is 110833.33?

Can you tell me what is the correct output of your calculations?
if 200000,
and assume 5.35%

What is the monthly payment? if my assumptions above is incorrect....
What is my new balance if i pay that amount?
What's the next?

Sorry for asking you that way,
Because i need a specific question and answer...

In calculation, if A and B = C and all other variables is dependent on C, and if C got the wrong answer, then all computation will also lead to a wrong answer.

Correct me if im wrong,
Sukatoa
Mar 3 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2439
by: Rhino | last post by:
I'm trying to debug a simple Java UDF written in the DB2General style within Eclipse. I'm getting a java.lang.UnsatisfiedLinkError when I execute the set() method in the UDF. I know that the UnsatisfiedLinkError has something to do with a DLL that is not visible but I'm not sure why I'm having the problem given that both db2java.zip and db2jcc.jar are visible on my classpath and each of them contain the COM.ibm.db2.app.UDF class with a...
4
6984
by: promiscuoustx | last post by:
The problem is that my code below used to run wonderfully, until the instructor decided that he wants to use characters instead of integers, and wants my code to trap the bad and have the program state that the user did not imput the correct values. Can someone help me figure out how to make my code work that way??? I have the majority of the code done.....but....I still need that last step!! Thanks!! #include <iostream> #include...
3
4036
by: promiscuoustx | last post by:
I am trying to get my program to compile, but it will not complete. At line 79 it states, cannot convert 'float()()' to 'float' in assignment. Here is my code. #include <iostream> #include <iomanip> #include <cmath> #include <cctype> #include <stdlib.h> #include <sstream> using namespace std;
7
13270
by: ibtc209 | last post by:
I just started programming in C, and I need some help with this problem. Your program will read the information about one MiniPoker hand, namely the rank and suit of the hand’s first card, and the rank and suit of its second card. Note that the two cards in a hand may be entered in any order; it’s not necessarily the case that the highest card will appear first, for example. Your program will then determine whether the hand is valid, and...
3
6702
by: cameron | last post by:
Hi I am new here in this forum: I am writing a C++ program to calculate a Montly Mortgage Payment where the loan amount is 200,000.00 with a 5.75% interest rate with a term of 30 years. My program compiles fine with no errors but my calculation is not working correctly, any suggestions would be great as this assignment is due on Monday: //******************************************************* //Program: Calculations Payments //Purpose: To...
2
7891
by: phjones | last post by:
Need help programming mortagage calculator for 3 different loans 7 year, 15 year and 30 year. using java array I am a beginner with Java, This is what I have so far. Need to know if I am off the path, import java.math.*;//*loan calculator import java.text.*;//*formats numbers public class 3 Mortgage loans { // declare class variable array int mortgage calculator
3
1993
by: pnolan | last post by:
Hello there, I'm brand new to Java and have. I'm taking my 2nd Java class at school and I'm pretty lost at this point. The main problem I'm having right now is I cannot get my code to execute. My code will compile, but when I try to execute it, either just using the "java" command or executing from TextPad, I get the following error: Exception in thread "main" java.lang.NoClassDefFoundError: MortgagePayment1 Press any key to continue ....
3
1507
by: poojagupta1984 | last post by:
What i know is: In java, all byte and short data types are automatically promoted to int during a calculation. And, if you are casting a large data type like int to a byte then the int is reduced modulo the range of the short data type i.e byte (the range of byte is 256). The program below has no compilation error. The output is incorrect for the first print statement..please explain why? class TestByte { public static void...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.