Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-11-2009, 09:23 PM
Member
 
Join Date: Nov 2008
Posts: 14
Rep Power: 0
Laura Warren is on a distinguished road
Default Variable Scope
Hello:

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.

Thanks!

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();
Mortgageframe.setVisible(true);
}
} //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);
centerWindow(this);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new MortgagePanel();
this.add(panel);
}
// 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: ");
topPanel.add(loanAmountLabel);
loanAmountTextField = new JTextField(11);
topPanel.add(loanAmountTextField);

//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 (Color.red);
errorPanel.add(errorlbl);

//this section creates the area for the option box

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

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

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

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


//this section contains settings for table listing
paymentsTable = new JTable();
table = new DefaultTableModel(columnHeadings,4);
paymentsTable.setModel(table);
paymentsTable.setPreferredScrollableViewportSize(n ew Dimension
(500, 100));
paymentsTable.setFillsViewportHeight(true);
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");
calculateButton.addActionListener(this);
buttonPanel.add(calculateButton);

resetButton = new JButton("Reset");
resetButton.addActionListener(this);
buttonPanel.add(resetButton);

exitButton = new JButton("Exit");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);

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

this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));;
this.add(topPanel,BorderLayout.CENTER);
this.add(errorPanel,BorderLayout.CENTER);
this.add(optionPanel,BorderLayout.CENTER);
this.add(monthlyPaymentPanel,BorderLayout.CENTER);
this.add(totalInterestPanel,BorderLayout.CENTER);
this.add(totalPrinPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.CENTER);
this.add(paymentsScrollPane,BorderLayout.SOUTH);

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)
System.exit(0);
// Calculate button has been clicked
if (source == calculateButton)
{
resetTable();
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");
loanAmountTextField.requestFocus();
}

else //loan amount is not blank
{

try
{
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",
JOptionPane.ERROR_MESSAGE);

loanAmountTextField.setText("");
loanAmountTextField.requestFocus();
}

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

//select rate and term from combination box
switch (optionsCombo.getSelectedIndex())
{
case 0:
interestRate = 5.35;
years = 7;
break;
case 1:
interestRate = 5.5;
years= 15;
break;
case 2:
interestRate = 5.75;
years = 30;
break;
} // 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
(InterestPaid);

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


monthlyPaymentTextField.setText(PmtFormat.format
(monthlyPayment));
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)
{
loanAmountTextField.setText("");
monthlyPaymentTextField.setText("");
errorlbl.setText(" ");
resetTable();
}//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
__________________
Laura

Last edited by Laura Warren; 01-11-2009 at 09:44 PM.
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 01-11-2009, 09:53 PM
Fubarable's Avatar
Moderator
 
Join Date: Jun 2008
Posts: 3,195
Rep Power: 5
Fubarable is on a distinguished road
Default
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:
Code:
          monthlyPaymentTextField.setText(PmtFormat.format(monthlyPayment));
          //totalInterestTextField.setText(PmtFormat.format(totalInterest)); // wrong!
          totalInterestTextField.setText(PmtFormat.format(CumInterest)); // right!
          totalPrincipalField.setText(PmtFormat.format(totalPrincipal));
          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 [code] at the top of your block of code and the tag [/code] at the bottom, like so:

Code:
[code]
  // your code block goes here.
  // note the differences between the tag at the top vs the bottom.
[/code]
Best of luck!

Last edited by Fubarable; 01-11-2009 at 09:56 PM.
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 01-11-2009, 10:04 PM
Member
 
Join Date: Nov 2008
Posts: 14
Rep Power: 0
Laura Warren is on a distinguished road
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!!!
__________________
Laura
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 01-11-2009, 10:16 PM
Member
 
Join Date: Nov 2008
Posts: 14
Rep Power: 0
Laura Warren is on a distinguished road
Default
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,
__________________
Laura
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
jsf scope query nc_newie JavaServer Faces 1 08-06-2008 02:34 PM
return out of scope? another_steve New To Java 5 01-28-2008 09:34 PM
How to use session scope in Spring JavaBean Java Tips 0 09-28-2007 12:47 PM
How to use request Scope in Spring JavaBean Java Tips 0 09-28-2007 12:46 PM
How to define Bean Scope JavaBean Java Tips 0 09-26-2007 08:43 PM


All times are GMT +2. The time now is 03:12 AM.



VBulletin, Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org