[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

6.6

Mortgage Calculator GUI w/user input  or menu selection

Asked by sybermon in Java Programming Language

This program calculates mortgage payment.based on  user input of the amount of the mortgage and the user's selection from a menu of available mortgage loans:
The code only works if for one type of calculation.  The code below doesnt work.

      if(source == calcButton2)
      selButton.setText(principalDouble);
      selButton.setToolTipText(principalDouble);
      yearsField.setEditable(true);
      rateField.setEditable(true);
                        stringSelectionList.setEnabled(false);
                  }
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
491:
492:
493:
494:
495:
496:
497:
498:
499:
500:
501:
502:
503:
504:
505:
506:
507:
508:
509:
510:
511:
512:
513:
514:
515:
516:
517:
518:
519:
520:
521:
522:
523:
524:
525:
526:
527:
528:
529:
530:
531:
532:
533:
534:
535:
536:
537:
538:
539:
540:
541:
542:
543:
544:
545:
546:
547:
548:
549:
550:
551:
552:
553:
554:
555:
556:
557:
558:
559:
560:
561:
562:
563:
564:
565:
566:
567:
568:
569:
570:
571:
572:
573:
574:
575:
576:
577:
578:
579:
580:
581:
582:
583:
584:
585:
586:
587:
588:
589:
590:
591:
592:
593:
594:
595:
596:
597:
598:
599:
600:
601:
602:
603:
604:
605:
606:
607:
608:
609:
610:
611:
612:
613:
614:
615:
616:
617:
618:
619:
620:
621:
622:
623:
624:
625:
626:
627:
628:
629:
630:
631:
632:
633:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
 
import java.text.DecimalFormat;
 
public class MortgageCalculatorGUI3BK extends JFrame implements ListSelectionListener, ActionListener
{
 
	private static final long serialVersionUID = 1L;
	private JList stringSelectionList;
	private JTextField principalField;
	private JTextField principalField2;
	private JTextField yearsField;
	private JTextField rateField;
	private JTextField paymentField;
	private JButton calcButton1;
	private JButton calcButton2;
	private JButton Again; 
    private JButton Quit;
	private double principalDouble;
	private double rateDouble;
	private int yearsInt;
	private double[] rateArray = {5.35, 5.5, 5.75}; // add the rates to an array
	private int[] yearsArray = {7,15,30}; // add the term years to an array
	private JTextArea amortArea;
	private JScrollPane amortPane; // declaring as global so I can have access after action is performed
	
	public MortgageCalculatorGUI3BK()
	{
		super("Mortgage Calculator");
		// Setting the default close operations is VERY improtant.. if you don't tell the frame to exit,
		// it leave things running headless until you kill it. Its OK to not exit on close if the frame is 
		// not the primary screen for instance.
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		try
		{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		}
		catch(Exception e)
		{
			// good for debug.. but if this doesn't work, no harm done
			System.out.println(e.getMessage());
		}
		
		Container content = getContentPane();
		content.setLayout(new BorderLayout());
		content.setBackground(Color.LIGHT_GRAY);
		
		// set the display font for all the labels and fields
		Font displayFont = new Font("Serif", Font.BOLD, 18);
		
		// Create the JList, set the number of visible rows, add a
		// listener, and put it in a JScrollPane.
		String[] entries = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"};
		// the order of the values in the entries array is important. It must match the
		// order of the values entered into the rateArray and yearsArray above 
		stringSelectionList = new JList(entries);
		stringSelectionList.setVisibleRowCount(3);
		stringSelectionList.setToolTipText("Select the term and interest rate of your loan.");
		stringSelectionList.setFont(displayFont);
		// register us for changes in the selection
		stringSelectionList.addListSelectionListener(this);
		// make it so we can scroll - this will not be needed for just 3 entries
		// but it would be needed if there were several entries
		JScrollPane listPane = new JScrollPane(stringSelectionList);
		// create a panel to separate the list from the display
		JPanel listPanel = new JPanel();
		listPanel.setBackground(Color.LIGHT_GRAY);
		// create a boarder around the panel
		Border listPanelBorder = BorderFactory.createTitledBorder("Loan Menu");
		listPanel.setBorder(listPanelBorder);
		listPanel.add(listPane);
		// listPanel will be added to another Panel later
 
				
		// User Input Panel
		JLabel principalLabel = new JLabel("Principal to Borrow");
		principalLabel.setFont(displayFont);
		principalField = new JTextField("250000", 7); // initial value = 250000, 7 columns wide
		principalField.setEditable(true); // will be able to type in data...
		principalField.setFont(displayFont);
		principalField.setToolTipText("Enter a positive number"); // this shows up when user hovers over field
		JLabel yearsLabel = new JLabel("Term of Loan (in years)");
		yearsLabel.setFont(displayFont);
		yearsField = new JTextField(2); // no initial value, 2 columns
		yearsField.setEditable(false); // will NOT be able to type in data...
		yearsField.setFont(displayFont);
		yearsField.setToolTipText("Enter a positive whole number");
		JLabel rateLabel = new JLabel("Rate of Loan");
		rateLabel.setFont(displayFont);
		rateField = new JTextField(4); // no initial value, 4 columns
		rateField.setEditable(false); // will NOT be able to type in data...
		rateField.setFont(displayFont);
		rateField.setToolTipText("Enter a positive number");
		
		
	// create Panel to hold the components - use a Grid Layout to organize fields
JLabel principalLabel2 = new JLabel("Principal to Borrow");
principalLabel2.setFont(displayFont);
principalField2 = new JTextField("250000", 7); // initial value = 250000, 7 columns wide
principalField2.setEditable(true); // will be able to type in data...
principalField2.setFont(displayFont);
principalField2.setToolTipText("Enter a positive number"); // this shows up when user hovers over field
JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5)); // 2 rows, 2 columns
inputPanel.setBackground(Color.orange);
Border inputPanelBorder = BorderFactory.createTitledBorder("User Inputs"); // create a border title
inputPanel.setBorder(inputPanelBorder); // add the border title to the Panel
// add the components to the Panel
inputPanel.add(principalLabel2);
inputPanel.add(principalField2);
 
 
		
		
		// create Panel to hold the components - use a Grid Layout to organize fields
		JPanel selectPanel = new JPanel(new GridLayout(3,2,5,5)); // 3 rows, 2 columns
		selectPanel.setBackground(Color.ORANGE);
		Border selectPanelBorder = BorderFactory.createTitledBorder("Selected Inputs"); // create a border title
		selectPanel.setBorder(inputPanelBorder); // add the border title to the Panel
		// add the components to the Panel
		selectPanel.add(principalLabel);
		selectPanel.add(principalField);
		selectPanel.add(yearsLabel);
		selectPanel.add(yearsField);
		selectPanel.add(rateLabel);
		selectPanel.add(rateField);
		// inputPanel will be added to another Panel later
		
		// initially select the first record in the table
		// and because the listener for this JList is activated, it will take
		// the values of the selected entry and populate the Rate and Term fields
		// This will come in handy in later weeks when we read entries from a file
		// to populate our JList. The first entry will always be added to the fields also.
		stringSelectionList.setSelectedIndex(0);
		JPanel inputsPanel = new JPanel(new GridLayout(2,2,2,2)); // 2 row, 2 columns
		
		//Action and Payment Panel
		calcButton1 = new JButton("Calculate Payment 1 ");//This will start the mortgage calculation process
		calcButton1.setFont(displayFont);
		
		calcButton2 = new JButton("Calculate Payment 2");//This will start the mortgage calculation process
		calcButton2.setFont(displayFont);
 
        Again = new JButton("Again?"); // Button used to remove previous choices made by user
        Again.setFont(displayFont);
 
        Quit = new JButton("Quit"); // Button used to Quit program
       	Quit.setFont(displayFont);
 
        //This section "listens" for a response from user
      	calcButton1.addActionListener(this);
      	calcButton2.addActionListener(this);
        Again.addActionListener(this);
        Quit.addActionListener(this);
 
		// register to listen for the button click
		calcButton1.addActionListener(this);
		calcButton2.addActionListener(this);
	     Again.addActionListener(this);
        Quit.addActionListener(this);
		calcButton1.setToolTipText("Click this button to calculate the monthly payment");
		calcButton2.setToolTipText("Click this button to calculate the monthly payment");
		Again.setToolTipText("Click this button to start Againt");
			Quit.setToolTipText("Click this button to end the program");
		
		paymentField = new JTextField("", 10);
		paymentField.setFont(displayFont);
		paymentField.setEditable(false); // will NOT be able to type in data...
		JPanel paymentPanel = new JPanel(new GridLayout(2,1,5,5)); // 2 rows, 1 column
		paymentPanel.setBackground(Color.LIGHT_GRAY);
		Border outputPanelBorder = BorderFactory.createTitledBorder("Monthly Payment");
		paymentPanel.setBorder(outputPanelBorder);
			
		// add the field and button to a Panel
		paymentPanel.add(paymentField);
		paymentPanel.add(calcButton1);
		paymentPanel.add(calcButton2);
		paymentPanel.add(Again);
		paymentPanel.add(Quit);
		
		// add the 4 user interface Panels to the inputsPanel
		inputsPanel.add(listPanel);
		inputsPanel.add(inputPanel);
		inputsPanel.add(paymentPanel);
		inputsPanel.add(selectPanel);
		
		//Output Panel for Amortization Table
		JPanel amortPanel = new JPanel(new BorderLayout());
		amortPanel.setBackground(Color.YELLOW);
		Border amortPanelBorder = BorderFactory.createTitledBorder("Amortization Table");
		amortPanel.setBorder(amortPanelBorder);
		amortArea = new JTextArea(10,70); // set the preferred sized to 10 rows x 70 columns
		amortArea.setFont(displayFont);
		amortArea.setEditable(false); // will NOT be able to type in data...
		// add the amortArea to a JScrollPane so the user can scroll to see all the data
		amortPane = new JScrollPane(amortArea);
		amortPanel.add(amortPane); // add the Pane to the Panel
		
		// add the 2 main Panels to the container for this GUI
		content.add(inputsPanel, BorderLayout.CENTER);
		content.add(amortPanel, BorderLayout.SOUTH); 
		
		pack();
		// ok show the window.. code is already running, just need to make us visible
		setVisible(true);
	}
 
	/**
	 * This method is part of the ListSelectionListener interface. This method
	 * listens for the selection changes in the list, gets the selected value from
	 * the list and sets in the text field showing what was selected.
	 */
	public void valueChanged(ListSelectionEvent event)
	{
		if (!event.getValueIsAdjusting())// this makes sure we are not responding to multiple events
		{
			Object sourceList = event.getSource();
			// we "toString" the return, because the list can be any Java Object, and
			// we want he string representation of the object... in this case, both are
			// strings.
			if(sourceList == stringSelectionList)
			{
				// get the index number of the record selected
				int selectedInt = stringSelectionList.getSelectedIndex();
				// now read the appropriate record in the rateArray and yearsArray
				rateDouble = rateArray[selectedInt];
				yearsInt = yearsArray[selectedInt];
				// convert the values to strings and move them to their appropriate JTextField
				rateField.setText(Double.toString(rateDouble));
				yearsField.setText(Integer.toString(yearsInt));
			}
		}
	}
	
	public void actionPerformed(ActionEvent evt)
	{
		// create Strings to be used for error messages
		String strMessPrincipal = new String("Please enter a positive amount of Principal to Borrow.");
		String strMessRate = new String("Please enter a positive amount for the Interest Rate.");
		String strMessYears = new String("Please enter a postive whole number for the Term of the Loan.");
		
		Object source = evt.getSource();
		
		// check what sent the event... if its not our button, we don't do anything
	 
			if(source == calcButton1)
		{
			// The user clicked our button, so its time to do some work.
			// The code below will do the calculations 
			// get the contents of principalField
			String strPrincipal = principalField.getText();
			// check to be sure that a Principal Amount has been entered
			if(strPrincipal.length() == 0)
			{
				this.showMessage(strMessPrincipal); //Display error message
				// no work to do, so return
				return;
			}
			else{
				try { //convert the String to a Double - Catch an exception if user did not enter a number
					strPrincipal = strPrincipal.replaceAll(",", "");// remove commas
					principalDouble = Double.parseDouble(strPrincipal);
					if(principalDouble <= 0) //if negative or zero is entered throw a generic exception to get the user defined error message
					{
						throw new Exception();
					}
				} catch (Exception e) {
					this.showMessage(strMessPrincipal); //Display error message
					// no work to do, so return
					return;
				}
			}
			
			// get the contents of rateField
			String strRate = rateField.getText();
			// check to be sure that a rate amount has been entered
			if(strRate.length() == 0)
			{
				this.showMessage(strMessRate); //Display error message
				// no work to do, so return
				return;
			}
			else{
				try { //convert the String to a Double - Catch an exception if user did not enter a number
					strRate = strRate.replaceAll(",", "");// remove commas
					rateDouble = Double.parseDouble(strRate);
					rateDouble = rateDouble/100; //divide by 100 to turn into a percentage (6.25 becomes .625)
					if(rateDouble <= 0) //if negative or zero is entered throw a generic exception to get the user defined error message
					{
						throw new Exception();
					}
				} catch (Exception e) {
					this.showMessage(strMessRate); //Display error message
					// no work to do, so return
					return;
				}
			}
			
			// get the contents of yearsField
			String strYears = yearsField.getText();
			// check to be sure that a year integer has been entered
			if(strYears.length() == 0)
			{
				this.showMessage(strMessYears); //Display error message
				// no work to do, so return
				return;
			}
			else{
				try { //convert the String to an Integer - Catch an exception if user did not enter a number
					strYears = strYears.replaceAll(",", "");// remove commas
					yearsInt = Integer.parseInt(strYears);
					if(yearsInt <= 0) //if negative or zero is entered throw a generic exception to get the user defined error message
					{
						throw new Exception();
					}
				} catch (Exception e) {
					this.showMessage(strMessYears); //Display error message
					// no work to do, so return
					return;
				}
				
				
			if(source == calcButton2)
			 	selButton.setText(principalDouble);
				selButton.setToolTipText(principalDouble);
				yearsField.setEditable(true);
				rateField.setEditable(true);
				stringSelectionList.setEnabled(false);
			}
			
			// create an instance of the MortgageCalculator Class
			MortgageCalculator myMort = new MortgageCalculator(principalDouble, rateDouble, yearsInt);
			// call the method to get the Payment Amount
			Double paymentDouble; // create a Double to hold the payment Amount from myMort
			String strPayment; // create a string for payment amount so it can be set in paymentField
			paymentDouble = myMort.getMonthlypayment();
			
			// use the DecimalFormat so the strPayment can be limited to 2 decimals
			DecimalFormat df = new DecimalFormat("#0.00");
			// convert the the Double to a String with 2 decimals
			strPayment = df.format(paymentDouble);
			// set the value in the GUI
			paymentField.setText(strPayment);
			// get the Amortization Table values and move them into the amortTable field
			amortArea.setText(myMort.getAmortizationTableAsString());
			// now move to the top of the amortArea text area by setting the Caret Position to 0
			// If I did not do this step then the user would start at the bottom of
			// the Amortization Table data
			amortArea.setCaretPosition(0);
			// all done
		}
			//  This code clears all the text input fields to allow the user to start over
			if(source == Again)
	   			{
       			 paymentField.setText(null);
       			 yearsField.setText(null);
       			 rateField.setText(null);
       			 principalField.setText(null);
      			 }	
      			 
      			//  This code ends the program and closes the window	 	
			if (source == Quit)
				{
				System.exit(0);
         	     	}
	             }
 
	/**
	 * This method will display a pop-up message box to the user.
	 * 
	 * @param str - a string value to be displayed in the message box
	 */
	private void showMessage(String str) // Display a message to the GUI
	{
		JOptionPane.showMessageDialog(this, str);
	}
	
	public static void main(String[] args)
	{
		new MortgageCalculatorGUI3BK(); // creates the GUI by calling the constructor
	}
 
}
 
 
------------------------------------------ 
import java.text.NumberFormat;
 
/**
 * 
 * This is an example of the final week 5 PRG 420 mortgage calculator. You may use this or
 * modify it for your PRG 421 project provided you properly site my contribution
 * to your code.
 
 * @author Chip Dickson
 */
public class MortgageCalculator
{
	// member variables
	private double principal = -1.0;
	private double annualInterest = -1.0;
	private int years = -1;
	private double monthlyInt = -1.0;
	private int numberofpayments = -1; // total number of payments for loan
	private double monthlypayment = -1;
	// use these to fill the numbers needed to build the amortization table..
	// the goal is to keep all calculations out of any method that outputs data.
	private double[] interest_paid = null;
	private double[] principal_paid = null;
	private double[] balance = null;
	private double[] previous_balance = null;
	private NumberFormat fmt = NumberFormat.getInstance();
 
	/**
	 * @param principal
	 * @param annualInterest
	 * @param years
	 */
	public MortgageCalculator(double principal, double annualInterest, int years)
	{
		// you can use the "this" object to clarify any ambiguous variables
		this.principal = principal;
		this.annualInterest = annualInterest;
		this.years = years;
		// note that you do not need "this" to access a member variable
		monthlyInt = annualInterest / 12;
		numberofpayments = years * 12;
		// now that we know how many payments we have, we can allocate our
		// amortization
		// table arrays...
		interest_paid = new double[numberofpayments];
		principal_paid = new double[numberofpayments];
		balance = new double[numberofpayments];
		previous_balance = new double[numberofpayments];
		// set up the number formatter... BTW there is also a currency formatter
		fmt.setGroupingUsed(true);
		fmt.setMaximumFractionDigits(2);
		fmt.setMinimumFractionDigits(2);
		// might as well calculate the payment.. we have all the information
		// note how I call the method here... because it is part of this class
		calculatePayment();
		buildAmortizationTable();
	}
 
	/**
	 * Caluclates the monthly payment.
	 */
	private void calculatePayment()
	{
		monthlypayment = (principal * monthlyInt) / (1 - Math.pow(1 / (1 + monthlyInt), years * 12));
	}
 
	public double getMonthlypayment()
	{
		return monthlypayment;
	}
 
	public void buildAmortizationTable()
	{
		int paymentnumber = 0;
		double mnth_balance = principal;
		double mnth_interest;
		double princ;
		// might be better to use a for loop here.. but we will go with a while
		// loop
		while (paymentnumber < numberofpayments)
		{
			previous_balance[paymentnumber] = mnth_balance;
			mnth_interest = mnth_balance * (annualInterest / 12);
			interest_paid[paymentnumber] = mnth_interest;
			princ = monthlypayment - mnth_interest;
			principal_paid[paymentnumber] = princ;
			mnth_balance = mnth_balance - princ;
			balance[paymentnumber] = mnth_balance;
			paymentnumber++;
		}
	}
 
	/**
	 * Builds a displayable amortization table.
	 * 
	 * @return
	 */
	public String getAmortizationTableAsString()
	{
		StringBuffer buffer = new StringBuffer();
		int paymentnumber = 0;
		buffer.append("Payment #\tBalance\t\t   Principle Paid   \t  Interest Paid\t\t   New Balance \n");
		while (paymentnumber < numberofpayments)
		{
			// Show a full year of payments and then add a separator for the next year
			buffer.append((paymentnumber + 1) + "\t   $" + fmt.format(previous_balance[paymentnumber]) + "\t\t   $"
				+ fmt.format(principal_paid[paymentnumber]) + "\t\t   $" + fmt.format(interest_paid[paymentnumber])
				+ "\t\t   $" + fmt.format(balance[paymentnumber]) + "\n");
			// the % is the mod operator. It returns the remainder of the left
			// hand side
			// divided by the right using interger division. So this executes
			// only when paymentnumber+1 if evenly divisable
			// by 12... 12, 24, 36 etc.
			if ((paymentnumber + 1) % 12 == 0)
			{
				buffer.append("\n-------------------------------------------------------------------------\n");
			}
			paymentnumber++;
		}
		return buffer.toString();
	}
 
	// finally we add the getters and setters for things...
	/**
	 * @return Returns the annualInterest.
	 */
	public double getAnnualInterest()
	{
		return annualInterest;
	}
 
	/**
	 * @param annualInterest
	 *            The annualInterest to set.
	 */
	public void setAnnualInterest(double annualInterest)
	{
		this.annualInterest = annualInterest;
		monthlyInt = annualInterest / 12;
		// calculate the new values
		calculatePayment();
		buildAmortizationTable();
	}
 
	/**
	 * @return Returns the principal.
	 */
	public double getPrincipal()
	{
		return principal;
	}
 
	/**
	 * @param principal
	 *            The principal to set.
	 */
	public void setPrincipal(double principal)
	{
		this.principal = principal;
		// calculate the new values
		calculatePayment();
		buildAmortizationTable();
	}
 
	/**
	 * @return Returns the years.
	 */
	public int getYears()
	{
		return years;
	}
 
	/**
	 * @param years
	 *            The years to set.
	 */
	public void setYears(int years)
	{
		this.years = years;
		numberofpayments = years * 12;
		// need to re-allocate all the arrays
		interest_paid = new double[numberofpayments];
		principal_paid = new double[numberofpayments];
		balance = new double[numberofpayments];
		previous_balance = new double[numberofpayments];
		// calculate the new values
		calculatePayment();
		buildAmortizationTable();
	}
 
	/**
	 * @return Returns the monthlyInt.
	 */
	public double getMonthlyInt()
	{
		return monthlyInt;
	}
 
	/**
	 * @return Returns the numberofpayments.
	 */
	public int getNumberofpayments()
	{
		return numberofpayments;
	}
 
	/**
	 * This is the entry point to the application. No calculation here, just
	 * creating the classes and calling a few methods.
	 * 
	 * @param args
	 */
//	public static void main(String args[])
//	{
//		// now your mortgage calculator can be used for any input...
//		MortgageCalculator my_mort = new MortgageCalculator(355000, .0535, 15);
//		System.out.print(my_mort.getAmortizationTableAsString());
//		// now you can use the class manually too
//		my_mort.setAnnualInterest(.055);
//		my_mort.setPrincipal(355000);
//		my_mort.setYears(15);
//		System.out.print(my_mort.getAmortizationTableAsString());
//		// or create another instance
//		MortgageCalculator my_mort2 = new MortgageCalculator(355000, .0575, 30);
//		System.out.print(my_mort2.getAmortizationTableAsString());
//	}
}
[+][-]08/14/09 11:25 PM, ID: 25104368Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zone: Java Programming Language
Sign Up Now!
Solution Provided By: a_b
Participating Experts: 1
Solution Grade: B
 
[+][-]08/13/09 09:25 PM, ID: 25095255Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08/14/09 05:05 PM, ID: 25103321Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/14/09 11:22 PM, ID: 25104359Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08/15/09 09:57 AM, ID: 25106062Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/15/09 11:48 AM, ID: 25106439Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08/15/09 08:18 PM, ID: 25107709Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/16/09 09:06 AM, ID: 25109375Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091111-EE-VQP-92 - Hierarchy / EE_QW_3_20080625