Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: Looping help needed for math calculation

  1. #1
    Junior Member
    Join Date
    Sep 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Looping help needed for math calculation

    The monthly payment only returns "NaN" and the amortization does not display at all. I'm pretty sure my problem lies in my looping but i'm lost and unable to find it. HELP!!!!!

    import java.awt.*;
    import java.awt.event.*;
    import java.math.*;
    import java.text.*;
    import java.lang.*;
    import java.util.Locale;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.JOptionPane;
     
     
    public class Mortgage3 extends JFrame implements ActionListener {
     
    	double principal = 0;															//principal
    	int length = 0;																	//years
    	int months = 0;																	//months
    	double interestRate = 0;  														//interest rate
    	double monthlyInterest = 0;														//monthly interest rate
    	double monthlyPayment = 0;														//monthly payment
    	double premium = 0;																//premium
        double interestPaid = 0;  														//interest paid
        double balance = principal;														//balance
     
    	DecimalFormat money = new DecimalFormat("$0.00");       						//formats to 2 decimal places
     
        JPanel row1 = new JPanel();
        JLabel mortgage_label = new JLabel("Pam's Mortgage Calculator", JLabel.CENTER);
     
        JPanel row2 = new JPanel(new GridLayout(1, 2));
        JLabel principal_label = new JLabel("Enter Mortgage Amount (do not enter $ or cents):",JLabel.LEFT);
        JTextField principal_txt = new JTextField(10);
     
        JPanel row3 = new JPanel(new GridLayout(1, 2));
        JLabel button_label = new JLabel("Please select one of the following options:", JLabel.CENTER);
     
    	JPanel row4 = new JPanel(new GridLayout(1, 3));
    	JRadioButton oneButton = new JRadioButton("7 years at 5.35%",true);				//creates buttons
    	JRadioButton twoButton = new JRadioButton("15 years at 5.5%");
    	JRadioButton threeButton = new JRadioButton("30 years at 5.75%");
     
    	JPanel row5 = new JPanel(new GridLayout(1, 2));
        JLabel monthlyPayment_label = new JLabel("Your monthly payment will be:", JLabel.LEFT);
        JTextField monthlyPayment_txt = new JTextField(10);
     
    	JPanel row6 = new JPanel(new GridLayout(1, 2));
        JButton resetButton = new JButton("Reset");
        JButton exitButton = new JButton("Exit");
        JButton calculateButton = new JButton("Calculate Monthly Payment");
        JButton amortizationButton = new JButton("Show Amortization");
     
        JTextArea displayArea = new JTextArea(10, 45);									//for amortization display
        JTextField number_txt = new JTextField(4);
        JTextField balance_txt = new JTextField(12);
        JTextField interestPaid_txt = new JTextField(12);
        JScrollPane scroll = new JScrollPane(displayArea);
     
    	public Mortgage3() {
     
              	super ("Pam's Mortgage Calculator");
              	setSize(750, 600);														//sets overall GUI size
              	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            	Container pane = getContentPane();
     
            	Border rowborder = new EmptyBorder( 10, 15, 5, 15 );					//sets spacing inside frame
     
              	pane.add(row1);
              	row1.setMaximumSize( new Dimension( 10000, row1.getMinimumSize().height));
              	row1.setBorder( rowborder);
     
              	pane.add(row2);
             	row2.add(principal_label);
              	row2.add(principal_txt);
              	row2.setMaximumSize( new Dimension( 10000, row2.getMinimumSize().height));
              	row2.setBorder( rowborder);
     
              	pane.add(row3);
              	row3.add(button_label);
              	row3.setMaximumSize( new Dimension( 10000, row3.getMinimumSize().height));
            	row3.setBorder( rowborder);
     
              	pane.add(row4);
              	ButtonGroup pickOneGroup = new ButtonGroup();									//creates group for buttons
        		pickOneGroup.add(oneButton);
    			pickOneGroup.add(twoButton);
    			pickOneGroup.add(threeButton);
    			row4.add(oneButton);
    			row4.add(twoButton);
    			row4.add(threeButton);
              	row4.setMaximumSize( new Dimension( 10000, row4.getMinimumSize().height));
            	row4.setBorder( rowborder);
     
            	pane.add(row5);
              	row5.add(monthlyPayment_label);
              	row5.add(monthlyPayment_txt);
              	monthlyPayment_txt.setEditable(false);									//user cannot alter this text
              	row5.setMaximumSize( new Dimension( 10000, row5.getMinimumSize().height));
              	row5.setBorder( rowborder);
     
    			pane.add(row6);
              	row6.add(resetButton);
             	row6.add(exitButton);
             	row6.add(calculateButton);
             	row6.add(amortizationButton);
              	row6.setMaximumSize( new Dimension( 10000, row6.getMinimumSize().height));
              	row6.setBorder( rowborder);
     
              	scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));        	//for amortization display
            	pane.add(scroll);
     
            	pane.setLayout(new BoxLayout( pane, BoxLayout.Y_AXIS));
              	setVisible(true);
              	setContentPane(pane);
     
    			oneButton.addActionListener(this);										//button one listener
    			twoButton.addActionListener(this);										//button two listener
    			threeButton.addActionListener(this);									//button three listener
              	resetButton.addActionListener(this);  									//reset listener
              	exitButton.addActionListener(this);										//exit listener
              	calculateButton.addActionListener(this);								//calculate listener
              	amortizationButton.addActionListener(this);								//amortization listener
            }
     
            public void actionPerformed(ActionEvent event) {
     
                    	Object command = event.getSource();
    //begins error message checking
                        if(command == calculateButton) {
                        	try {
                            	principal = Double.parseDouble(principal_txt.getText());
                            }
                                catch(NumberFormatException e) {
     
    //error message for principal amount
                               JOptionPane.showMessageDialog(null, "Dollar amounts only please! (ex. 300000)", "ERROR", JOptionPane.ERROR_MESSAGE);
                               }
                        }
     
    //resets all amounts to blank
                        if(command == resetButton)  {
    						principal_txt.setText(null);
                            monthlyPayment_txt.setText(null);
                            displayArea.setText(null);
                        }
     
    //exits the program
                        if(command == exitButton) {
                            System.exit(0);
                        }
     
    					if(command == calculateButton) {
    						double principal=Double.parseDouble(principal_txt.getText());	//retrieving the users input
     
      				    	if (event.getSource() == oneButton) {
           						length = 7;
           						interestRate = 5.35;
      		  				}
     
        						if (event.getSource() == twoButton) {
            						length = 15;
            						interestRate = 5.5;
        						}
     
        					    	if (event.getSource() == threeButton) {
          								length = 30;
          								interestRate = 5.75;
          							}
     
        					monthlyInterest = (interestRate/12)/100;					//Determines monthly interest rate
    						months = length * 12;										//Changes years to months
    						monthlyPayment	= .005+(principal*monthlyInterest/(1-(Math.pow((1+monthlyInterest),(-months)))));		//Determines monthlyPayment
    						String s = Double.toString(monthlyPayment);
    						monthlyPayment_txt.setText(s);
    					}
     
    					if(command == amortizationButton) {
    						double principal=Double.parseDouble(principal_txt.getText());	//retrieving the users input
     
    						for(int number = 0; number <= length - 1; number++) {
     
    							if (event.getSource() == oneButton) {
    	       						length = 7;
    	       						interestRate = 5.35;
    							}
     
    	       						if (event.getSource() == twoButton) {
    	        						length = 15;
    	        						interestRate = 5.5;
    	       						}
     
    	        						if (event.getSource() == threeButton) {
    	      								length = 30;
    	      								interestRate = 5.75;
    	        						}
     
    						monthlyInterest = (interestRate/12)/100;
    	                    months = length * 12;										//Changes years to months
    						monthlyPayment	= .005+(principal*monthlyInterest/(1-(Math.pow((1+monthlyInterest),(-months)))));		//Determines monthlyPayment
    						interestPaid = balance * monthlyInterest + .005;			//Determines interest paid amount
    	                    premium = monthlyPayment - interestPaid;					//Determines premium paid
    	                    balance = balance - premium;								//Determines loan balance
     
    						String titles = "Payment # \t MonthlyPayment \tLoan Balance \t Interest Paid";
    						displayArea.setText(titles);
    						displayArea.setText(number+"\t\t"+money.format(balance)+"\t\t"+money.format(interestPaid));
    						String s = Double.toString(number);
    						number_txt.setText(s);
    						balance_txt.setText(s);
    						interestPaid_txt.setText(s);
    						}
    					}
    }
    	public static void main(String[] args) {
    				Frame f = new Mortgage3();
    					f.show();
     
    	}
    }


  2. #2
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    If you can't troubleshoot and debug a "looping problem" you have no business dabbling in GUIs. May seem harsh to you, but it's true.

    Start again from scratch, and create a console app that either prompts for input or uses hard-coded data, which you can edit and change from run to run to make sures the results are consistently correct. When you have that working, go back to your GUI.

    And if you can't even get a console app working the way you need it to, you will have a shorter, mor analyzable program to post here and ask for help. I for one have no intention of going through reams of deeply (and poorly) indented GUI code to discover a logic problem. Maybe you'll get lucky and someone else will, but you can greatly improve your chances of getting help by showing the effort to simplify the problem.

    db

  3. #3
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Also, were you taught to import every Java package you have ever heard of? java.lang.* is imported by default, and I'm sure your code doesn't use half the imports at the top of the code, not to mention the redundant import of individual classes in addition to the star import.

    I suspect you copied most of that code from somewhere without understanding any of it. I'll be happy if you prove me wrong.

    db

  4. #4
    Junior Member
    Join Date
    Sep 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Looping help needed for math calculation

    Thank you for your poor response. I thought this was a HELP forum but i guess i was mistaken. I guess this is only a forum for BASHING newbies. Shame on you!

  5. #5
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Seeing as how you got told off on forums.devshed.com, you could help yourself to get better help by going through these two links
    How To Ask Questions The Smart Way
    SSCCE : Java Glossary

    db

  6. #6
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Quote Originally Posted by pcornacchione View Post
    Thank you for your poor response. I thought this was a HELP forum but i guess i was mistaken. I guess this is only a forum for BASHING newbies. Shame on you!
    So, you think you have the right to demand help without exerting the effort you could, to make your question more easily answered. Better get a paid tutor, public forums aren't for the likes of you.

    Ask yourself why hundreds or even thousands of other members seeking help on various problems do indeed get the help they seek, whereas all you have 'achieved' is being rude to some stranger on the internet at (at least) two forums.

    Then decide who should be ashamed.

    db

  7. #7
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Looping help needed for math calculation

    Quote Originally Posted by Darryl.Burke View Post
    So, you think you have the right to demand help without exerting the effort you could, to make your question more easily answered. Better get a paid tutor, public forums aren't for the likes of you.

    Ask yourself why hundreds or even thousands of other members seeking help on various problems do indeed get the help they seek, whereas all you have 'achieved' is being rude to some stranger on the internet at (at least) two forums.

    Then decide who should be ashamed.

    db
    Owned lmao

  8. #8
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Further, on reviewing every word I have posted here, I fail to find any unhelpful post nor any
    BASHING newbies.
    That suggests you are trying to garner sympathy in the hope that some poor sod will hand you the code on a golden platter. I certainly hope that doesn't happen, as it will deny you the opportunity to learn and grow.

    db

  9. #9
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Cross posted and told off for duplicate posting
    Mortgage Calculator With GUI - Java | Dream.In.Code - Page 2

    db

  10. #10
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Looping help needed for math calculation

    Too bad, someone just handed him the answer on dream.in.code

  11. #11
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Quote Originally Posted by Brt93yoda View Post
    Too bad, someone just handed him the answer on dream.in.code
    Unfortunately I had some problems logging in there And it's her, not him. Use Google

    Now she'll never bother to learn. And the questions will get less and less directed till even dream.in.code will give up on her.

    db

  12. #12
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Looping help needed for math calculation

    Come on guys, we are the friendly java community after all!

    Yeah the OP may not have not approached this thread in the best possible way but as a new member we should be doing our best to help and hope that they learn from our advice. We don't have to help complete code or do all the work but a gentle nudge in the right direction is all it takes..

    Everyone has to start somewhere and everyone has the right to learn from their mistakes.

    I appreciate your help guys but found the instant dismissal slightly inappropriate. Please don't take my comments the wrong way.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  13. #13
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    I ... found the instant dismissal slightly inappropriate.
    I'd like to know which post you regard as an "instant dismissal"

    db

  14. #14
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Looping help needed for math calculation

    Quote Originally Posted by Darryl.Burke View Post
    If you can't troubleshoot and debug a "looping problem" you have no business dabbling in GUIs. May seem harsh to you, but it's true.

    Start again from scratch, and create a console app that either prompts for input or uses hard-coded data, which you can edit and change from run to run to make sures the results are consistently correct. When you have that working, go back to your GUI.

    And if you can't even get a console app working the way you need it to, you will have a shorter, mor analyzable program to post here and ask for help. I for one have no intention of going through reams of deeply (and poorly) indented GUI code to discover a logic problem. Maybe you'll get lucky and someone else will, but you can greatly improve your chances of getting help by showing the effort to simplify the problem.

    db
    This first post seemed very dismissive rather than helpful.

    But like I say, don't take my comments in the wrong way. People post similar threads to the OP all the time. The only reason I got involved is because it was flagged by a few users.

    I appreciate the help you do here on a daily basis.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  15. #15
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Looping help needed for math calculation

    Quote Originally Posted by JavaPF View Post
    This first post seemed very dismissive rather than helpful.
    When I wrote it, I thought so too, which is why I added the line
    May seem harsh, but it's true
    before I posted it.

    The OP's response was totally uncalled-for
    Quote Originally Posted by pcornacchione View Post
    Thank you for your poor response. I thought this was a HELP forum but i guess i was mistaken. I guess this is only a forum for BASHING newbies. Shame on you!
    I don't believe spoonfeeding helps anyone. Also, I don't believe in encouraging someone new to Java and/or programming to bite off more than they can chew. The question posted here and on at least two other forums is very obviously a homework question; its' also painfully obvious that the student who posted the question has neglected more fundamental aspects of Java that must have been taught along the way and was simply looking for code to submit as her own, aka cheating.

    And that's the last I have to say on this topic, regardless of any reactions to what I have already said. No more clarifications, no confrontations. Take it or leave it.

    db

Similar Threads

  1. RPM Calculation
    By fobos3 in forum Algorithms & Recursion
    Replies: 2
    Last Post: September 21st, 2010, 08:53 AM
  2. Math Problem
    By kidsforsale in forum What's Wrong With My Code?
    Replies: 11
    Last Post: September 14th, 2010, 04:09 PM
  3. Question on my math
    By SwEeTAcTioN in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 25th, 2009, 05:42 PM
  4. Math in Java?
    By [Kyle] in forum Java Theory & Questions
    Replies: 3
    Last Post: September 23rd, 2009, 12:21 PM
  5. SQL Time Calculation
    By r12ki in forum JDBC & Databases
    Replies: 3
    Last Post: July 31st, 2009, 03:54 AM