Thread: Variable Scope
View Single Post
  #1 (permalink)  
Old 01-11-2009, 10:23 PM
Laura Warren Laura Warren is offline
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 10:44 PM.
Reply With Quote