Results 1 to 4 of 4

Thread: Variable Scope

  1. #1
    Laura Warren is offline Member
    Join Date
    Nov 2008
    Rep Power

    Default Variable Scope


    Sorry, but here's yet another mortgage calculator question. I'm trying to add accumulated fields for total interest paid and total principal paid. My problem is that I'm trying to use the variables from within a for construct.

    I've tried this several ways. I originally had a CalculatePayment method that also populated the amortization table. It worked fine to return the monthly payment but since there can only be one return value I needed a way to also access the accumulated interest and principal. I read that to return multiple values it's better to create a new class but I'm quite overwhelmed at this point (I've been at this for almost 3 days round the clock).

    I moved all the code back into my action performed method but still not able to fill total interest paid and total principal paid values on my interface.

    I spent all day yesterday on reading the term / interest values from a file but have left that part out so that I can concentrate on one problem at a time. If anyone can help, I'd be very grateful. I've pretty much reached the brain death stage.


    Here's my code (with many of the comments removed to save space):
    ================================================== ========
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;

    class WarrenMortgageAppWeek5
    public static void main(String[] args)
    JFrame Mortgageframe = new MortgageFrame();
    } //end of WarrenMortgageAppWeek5 class

    class MortgageFrame extends JFrame
    /* This section will set up the application window
    * and size it to fit the controls. It will also
    * call a routine called "centerWindow" to calculate
    * the user's screen size and center the application.
    * Finally it adds the panels that will hold the components.

    public MortgageFrame()
    setTitle("Laura Warren Mortgage Calculator Week 5"); //title of frame
    setSize(440, 420);
    JPanel panel = new MortgagePanel();
    // end MortgageFrame method

    private void centerWindow(Window w)
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    } // end of centerWindow method

    }// end of MortgageFrame class

    // This section will specify the controls (labels, text fields, and buttons)
    // It will also declare variables and arrays

    class MortgagePanel extends JPanel implements ActionListener
    private JLabel loanAmountLabel;
    private JTextField loanAmountTextField;
    private JLabel totalInterestLabel;
    private JTextField totalInterestTextField;
    private JLabel totalPrincipalLabel;
    private JTextField totalPrincipalField;
    private JLabel monthlyPaymentLabel;
    private JTextField monthlyPaymentTextField;
    private JLabel errorlbl;
    private JLabel rateAndTermLabel;
    private JComboBox optionsCombo;
    private JTable paymentsTable;
    private DefaultTableModel table;
    private JButton calculateButton;
    private JButton resetButton;
    private JButton exitButton;
    private JScrollPane paymentsScrollPane;
    int rows = 400; //months not likely to exceed this value
    int columns = 4;
    int years = 0;
    double monthlyRate = 0;
    String columnHeadings[] = { "Pmt #", "Beg Bal", "Principle", "Interest" };
    String[][]paymentData = new String[rows][columns];
    int[] TermYears = {7, 15, 30};
    double[] AnnualRate = {5.35, 5.5, 5.75};
    DecimalFormat PmtFormat = new DecimalFormat("$#,##0.00");

    /* This next section adds the components and panels to the frame.
    * The extra label field will display any error messages in red.
    * The frame will be divided into panels
    * The first is the top panel, which includes the loan amount entry field
    * The second contains the error label
    * The fourth contains the input fields for week 3 rate and term selection
    * The fifth is the option panel, which contains the combo box
    * The sixth is the display of the montly payment amount
    * The seventh contains the accumulated interest paid
    * The eighth contains the accumulated principal paid
    * The ninth contains the table that will display amortization

    public MortgagePanel()
    //this section creates the top panel
    //holds the user input section for loan amount

    JPanel topPanel = new JPanel();
    topPanel.setLayout (new FlowLayout());
    loanAmountLabel = new JLabel("Amount of Loan: ");
    loanAmountTextField = new JTextField(11);

    //this section creates the area for the feedback label
    //messages appear in red

    JPanel errorPanel= new JPanel();
    errorPanel.setLayout (new FlowLayout());
    errorlbl = new JLabel(" ");
    errorlbl.setForeground (;

    //this section creates the area for the option box

    JPanel optionPanel = new JPanel();
    optionPanel.setLayout(new FlowLayout());
    rateAndTermLabel = new JLabel("Rate / Term: ");
    String[]options = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"};
    optionsCombo = new JComboBox(options);

    //this section contains the calculated monthly payment amount
    JPanel monthlyPaymentPanel = new JPanel();
    monthlyPaymentLabel = new JLabel("Monthly Payment:");
    monthlyPaymentTextField = new JTextField(11);

    //this section contains the total interest paid amount
    JPanel totalInterestPanel = new JPanel();
    totalInterestLabel = new JLabel("Tot Interest Paid: ");
    totalInterestTextField = new JTextField(11);

    //this section contains the total principal paid amount
    JPanel totalPrinPanel = new JPanel();
    totalPrincipalLabel = new JLabel("Tot Principal Paid:");
    totalPrincipalField = new JTextField(11);

    //this section contains settings for table listing
    paymentsTable = new JTable();
    table = new DefaultTableModel(columnHeadings,4);
    paymentsTable.setPreferredScrollableViewportSize(n ew Dimension
    (500, 100));
    paymentsScrollPane = new JScrollPane(paymentsTable);

    //This section creates a panel to display the 3 buttons
    //(Calculate, Reset, and Exit)

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

    calculateButton = new JButton("Calculate");

    resetButton = new JButton("Reset");

    exitButton = new JButton("Exit");

    //adds all sections to the main window using the GridLayout structure

    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));;
    this.add(totalPrinPanel, BorderLayout.CENTER);
    this.add(buttonPanel, BorderLayout.CENTER);

    table.setDataVector(paymentData, columnHeadings);

    } //end of MortgagePanel method

    This section defines what happens when each button is clicked.
    * The Exit button will close the application.
    * The Reset button will clear all fields.
    * The Calculate button will test for missing loan amount
    * When valid loan amount is entered, the monthly payment calculates.

    public void actionPerformed(ActionEvent e) throws NumberFormatException
    Object source = e.getSource();

    // Exit button has been clicked

    if (source == exitButton)

    // Calculate button has been clicked
    if (source == calculateButton)
    errorlbl.setText(" ");
    double loanAmount = 0.0;
    double monthlyPayment = 0.0;

    double interestRate = 0.0;
    double totalInterest = 0.0;
    double totalPrincipal = 0.0;

    if(loanAmountTextField.getText().length() == 0)
    errorlbl.setText("Please enter Loan Amount");

    else //loan amount is not blank

    loanAmount = Double.parseDouble(loanAmountTextField.getText());
    } // end try

    catch(NumberFormatException p)
    //catch null pointer exception if Principal is null
    JOptionPane.showMessageDialog(null, "Invalid Entry! Please Try
    Again", "ERROR",


    if (loanAmount <=0)
    errorlbl.setText("Please enter a positive amount.");
    errorlbl.setText("Thank you!");

    //select rate and term from combination box
    switch (optionsCombo.getSelectedIndex())
    case 0:
    interestRate = 5.35;
    years = 7;
    case 1:
    interestRate = 5.5;
    years= 15;
    case 2:
    interestRate = 5.75;
    years = 30;
    } // end switch

    //format and place monthly payment calculation
    //call method to calculate values for Loan Amount
    //calculates table

    double monthlyRate = interestRate / 12 /100;
    int termMonths = years * 12;
    monthlyPayment = loanAmount * monthlyRate/(1-(1/Math.pow(1 + monthlyRate,termMonths)));

    //the problem is in here somewhere
    //declare and initialize variable for amortization calculations
    double BeginningBal = Double.parseDouble(loanAmountTextField.getText());
    double EndingBal;
    double Principal;
    double InterestPaid;
    double CumInterest = 0;

    //this section loops through all payments and calculates
    //Beginning Balance, Principle, and Interest Paid values

    for (int MonthCounter = 1; MonthCounter <= termMonths;
    MonthCounter++ )

    InterestPaid = BeginningBal * monthlyRate;
    Principal = monthlyPayment - InterestPaid;
    EndingBal = BeginningBal - Principal;
    CumInterest = CumInterest + InterestPaid;

    //this section will fill in table values row by row
    paymentData[MonthCounter-1][0] = ""+MonthCounter;
    paymentData[MonthCounter-1][1] = PmtFormat.format (BeginningBal);
    paymentData[MonthCounter-1][2] = PmtFormat.format(Principal);
    paymentData[MonthCounter-1][3] = PmtFormat.format

    //Ending Balance for one month becomes Beginning Balance for next
    BeginningBal = EndingBal;
    } // end for

    totalInterestTextField.setText(PmtFormat.format(to talInterest));
    totalPrincipalField.setText(PmtFormat.format(total Principal));

    table.setDataVector(paymentData, columnHeadings);

    } // loan amount entered
    } // loan amount blank

    }// end calculate button

    if (source ==resetButton)
    errorlbl.setText(" ");

    }//end if source reset
    //================================================== ======
    } // end ActionPerformed

    public void resetTable()
    //clear existing values from table
    for(int MonthCounter=0; MonthCounter<=360; MonthCounter++)
    paymentData[MonthCounter][0]=" ";
    paymentData[MonthCounter][1]=" ";
    paymentData[MonthCounter][2]=" ";
    paymentData[MonthCounter][3]=" ";
    table.setDataVector(paymentData, columnHeadings);
    errorlbl.setText("Values Cleared");

    } // end resetTable

    } // end MortgagePanel class
    Last edited by Laura Warren; 01-11-2009 at 10:44 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Blog Entries
    Rep Power


    You've already done the correct calculation for total interest (held by the CumInterest variable), but for some reason are using the wrong variable (the totalInterest variable)when trying to display the result in the JTextField.

    For instance:
    Java Code:
              //totalInterestTextField.setText(PmtFormat.format(totalInterest)); // wrong!
              totalInterestTextField.setText(PmtFormat.format(CumInterest)); // right!
              table.setDataVector(paymentData, columnHeadings);
    Myself, I'd take all the calculations out of the GUI and create a totally separate class just to do the calcs. I'd pass this class via its constructor the numbers necessary to do the calculations and then extract from this object the data necessary.

    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:

    Java Code:
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    Best of luck!
    Last edited by Fubarable; 01-11-2009 at 10:56 PM.

  3. #3
    Laura Warren is offline Member
    Join Date
    Nov 2008
    Rep Power

    Smile Thank You!!

    Thank you so much! I've been working at this so long it was staring me right in the face and I couldn't see it.

    Now I get to work more on reading rate and term from a file.

    Thanks again!!!

  4. #4
    Laura Warren is offline Member
    Join Date
    Nov 2008
    Rep Power


    Oops. I read only the first part of your comment when I responded last. Thanks for the tip about formatting the code. I'll remember that.

    Best regards,

Similar Threads

  1. jsf scope query
    By nc_newie in forum JavaServer Faces (JSF)
    Replies: 1
    Last Post: 08-06-2008, 02:34 PM
  2. return out of scope?
    By another_steve in forum New To Java
    Replies: 5
    Last Post: 01-28-2008, 10:34 PM
  3. How to use session scope in Spring
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 09-28-2007, 12:47 PM
  4. How to use request Scope in Spring
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 09-28-2007, 12:46 PM
  5. How to define Bean Scope
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 09-26-2007, 08:43 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts