Java mortgage calculator sequential file HELP...please

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

40 Replies - 12141 Views - Last Post: 20 September 2010 - 02:33 PM Rate Topic: -----

#1 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 08:30 AM

Hello there. I am beginning my last week of Java class and I now need to complete change request number 7. I have successfully completed my program each week up until now (with a little help...)but I now have to create a .txt file called "term" to store the interest rate to be read by the program. I have read my text and found various examples of writing and reading sequential files, but I can not figure out where to put the new code inside my existing code to make it work. Here aare the instructions for this week...I basically need to read my interest rates from a file, and add a functioning chart or graph to the GUI. I have a till Monday to get this right, if someone could please take a look at my code and help me figure out how to get started to create the term.txt file and get my program to read it I would really appreciate any help I can get.

Write the program in Java (with a graphical user interface) and have it calculate and display the mortgage payment amount from user input of the amount of the mortgage and the user's selection from a menu of available mortgage loans:
- 5 years at 5% - 7 years at 5.35% - 15 years at 5.5 % - 30 years at 5.75%

Use an array for the mortgage data for the different loans. Read the interest rates to fill the array from a sequential file. Display the mortgage payment amount followed by the loan balance and interest paid for each payment over the term of the loan. Add graphics in the form of a chart. Allow the user to loop back and enter a new amount and make a new selection or quit. Please insert comments in the program to document the program.


I know I need to put something like this in there, but I just don't know where to start making the adjustments:

input = new DataInputStream(new FileInputStream(existingFilename));


Here is my code for last weeks assignment and it works very well......

/** Mortgage Calculator Program
 * Week 4 PRG421
 *Change request #6
 *Write the program in Java (with a graphical user interface) so that it will
 * allow the user to select which way they want to calculate a mortgage:
 * by input of the amount of the mortgage, the term of the mortgage, and the
 * interest rate of the mortgage payment or by input of the amount of a mortgage
 * and then select from a menu of mortgage loans:

- 5 years at 5%
- 7 years at 5.35%
- 15 years at 5.5 %
- 30 years at 5.75%

In either case, display the mortgage payment amount and then,
 list the loan balance and interest paid for each payment over
  the term of the loan. Allow the user to loop back and enter a new
   amount and make a new selection, or quit. Insert comments in the program to document the program.


*
*Author: Stacey Estey
*Due September 13, 2010*/


//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;


//declare calculator class
public class Calculator extends JFrame
 {
private String [] terms = {"5","7", "15", "30"};
private double [] rates = {0.05, 0.0535, 0.55, 0.0575};
private JLabel amountLabel = new JLabel ("Mortgage Amount:");
private JTextField amount = new JTextField();
private JLabel termLabel = new JLabel ("Term of Loan:");
private JTextField term = new JTextField();
private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
private JTextField rate = new JTextField();
private JComboBox termList = new JComboBox(terms);
private JLabel payLabel = new JLabel("Monthly Payment:");
private JLabel payment = new JLabel();
private JButton calculate = new JButton("Calculate");
private JButton clear = new JButton("Clear");
private JButton exit = new JButton("Exit");
private JTextArea paymentSchedule = new JTextArea();
private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
private Container cp = getContentPane();

	public Calculator(String title)
	{
		super.setTitle(title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//handle term list
		termList.setSelectedIndex(0);
		termList.addActionListener(new ActionListener()		{
			public void actionPerformed(ActionEvent e){
				JComboBox cb = (JComboBox)e.getSource();
				String termYear = (String)cb.getSelectedItem();
				term.setText(termYear);
				int index = 0;
				switch (Integer.parseInt(termYear)){
					case 5: index = 0; break;
					case 7: index = 1; break;
					case 15: index = 2; break;
					case 30: index = 3; break;
				}
				rate.setText(rates[index] + "");
			}
		});


		//handle the button events
	calculate.addActionListener(new ActionListener(){

		public void actionPerformed(ActionEvent e){

			try{
				//calculate the payments.
				double p = Double.parseDouble(amount.getText());
				double r = Double.parseDouble(rate.getText()) / 12;
				double n = Integer.parseInt(term.getText()) * 12;
				double monthlyPayment = p * Math.pow (1 + r, n) * r / (Math.pow(1 + r, n)- 1);
				DecimalFormat df = new DecimalFormat("$###,###.00");
				payment.setText(df.format(monthlyPayment));


				//calculate the loan information

				double principal = p;
				int month;
				StringBuffer buffer = new StringBuffer();
				buffer.append("Month\tAmount\tInterest\tBalance\n");
				for (int i = 0; i < n; i++){
					month = i + 1;
					double interest = principal * r;
					double balance = principal + interest - monthlyPayment;
					buffer.append(month + "\t");
					buffer.append(new String(df.format(principal)) + "\t");
					buffer.append(new String(df.format(interest)) + "\t");
					buffer.append(new String(df.format(balance)) + "\n");
					principal = balance;

				}
				paymentSchedule.setText(buffer.toString());
			} catch (Exception ex) {
				System.out.println(ex);
			}
		}
	});

	clear.addActionListener(new ActionListener(){

		public void actionPerformed(ActionEvent e){
			term.setText("");
			rate.setText("");
			amount.setText("");
			payment.setText("");
			paymentSchedule.setText("");
		}
	});


	exit.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			System.exit(1);
		}

	});

	JPanel calcScreen = new JPanel();
	calcScreen.setLayout(new GridLayout(10,4));
	calcScreen.add(amountLabel);
	calcScreen.add(amount);
	calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
	calcScreen.add(termList);
	calcScreen.add(termLabel);
	calcScreen.add(term);
	calcScreen.add(rateLabel);
	calcScreen.add(rate);
	calcScreen.add(payLabel);
	calcScreen.add(payment);

	JPanel buttons = new JPanel();
	buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
	buttons.add(calculate);
	buttons.add(clear);
	buttons.add(exit);

	JPanel calc = new JPanel();
	calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
	calc.add(calcScreen);
	calc.add(buttons);
	cp.add(BorderLayout.NORTH, calc);
	cp.add(BorderLayout.CENTER, schedulePane);

	}

	public static void main(String[] args)
	{
		Calculator frame = new Calculator("Mortgage Calculator");
		frame.setSize(400,600);
		Frame.setVisible(true);


	}

}


Is This A Good Question/Topic? 0
  • +

Replies To: Java mortgage calculator sequential file HELP...please

#2 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 08:47 AM

Some one else came up here with something equal to your assignment. Check this thread.
Was This Post Helpful? 1
  • +
  • -

#3 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 09:19 AM

View Postguidojavier, on 15 September 2010 - 07:47 AM, said:

Some one else came up here with something equal to your assignment. Check this thread.


I read through the thread and code that you suggested but since that program is set up totally different than mine I am still not getting it. My "String" in my program is just the years, then my intrest rates are double...stored separately.
private String [] terms = {"5","7", "15", "30"};
private double [] rates = {0.05, 0.0535, 0.55, 0.0575};


My text file has four entries and no comma's, which are
0.05
0.0535
0.55
0.575

I know this probably seems trivial to someone who knows about Java, but it's really giving me grief. You would thin that when you spend $1,700.00 + for each five week class you could get better guidance from an instructor...but unfortunately I have to find help elsewhere. I appreciate your input.

Attached File(s)

  • Attached File  term.txt (27bytes)
    Number of downloads: 192

Was This Post Helpful? 0
  • +
  • -

#4 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 09:42 AM

So the only thing that you are going to read from the text file are the rates. You said that your problem is that you do not know where you should place the necesary code in order to load the file and read the rates. You should have a check box where the user
can choose between using the default rates or loading them from a text file. Then you write a listener for this check box and within it you invoke a method which load the file. Something like:
  FileReader fr = new FileReader("rates.txt");
  BufferedReader reader = new BufferedReader(fr);
  int index = 0;
  while(reader.readLine() != null)
  {
      ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
      i++;
  }
                      
  reader.close();


Load the rates into a new array. So if the check box has been selected you work with the values in the new array. If the check box has not been selected you work with the values in the other array.

This post has been edited by guidojavier: 15 September 2010 - 09:44 AM

Was This Post Helpful? 1
  • +
  • -

#5 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 10:54 AM

View Postguidojavier, on 15 September 2010 - 08:42 AM, said:

So the only thing that you are going to read from the text file are the rates. You said that your problem is that you do not know where you should place the necesary code in order to load the file and read the rates. You should have a check box where the user
can choose between using the default rates or loading them from a text file. Then you write a listener for this check box and within it you invoke a method which load the file. Something like:
  FileReader fr = new FileReader("rates.txt");
  BufferedReader reader = new BufferedReader(fr);
  int index = 0;
  while(reader.readLine() != null)
  {
      ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
      i++;
  }
                      
  reader.close();


Load the rates into a new array. So if the check box has been selected you work with the values in the new array. If the check box has not been selected you work with the values in the other array.


Thank you so much...I now have a clear idea of what I need to do for this part of the assignment. =) I really think I can get this now!
Was This Post Helpful? 0
  • +
  • -

#6 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 12:10 PM

I have taken your advice, and think I am on the right track, but I am getting two errors:

Quote

--------------------Configuration: <Default>--------------------
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:131: illegal start of expression
while(reader.readLine()) ! = null)
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:131: ';' expected
while(reader.readLine()) ! = null)
^
2 errors

Process completed.


Here is my updated code:
/** Mortgage Calculator Program
 * Week 4 PRG421
 *Change request #7
 *Write the program in Java (with a graphical user interface) and have it
 * calculate and display the mortgage payment amount from user input of the
 * amount of the mortgage and the user's selection from a menu of available
 * mortgage loans:
 *
- 5 years at 5%
 - 7 years at 5.35%
 - 15 years at 5.5 %
 - 30 years at 5.75%

Use an array for the mortgage data for the different loans.
 Read the interest rates to fill the array from a sequential file.
  Display the mortgage payment amount followed by the loan balance and interest
   paid for each payment over the term of the loan. Add graphics in the form of a chart.
    Allow the user to loop back and enter a new amount and make a new selection or quit.
     Please insert comments in the program to document the program.
*
*Author: Stacey Estey
*Due September 20, 2010*/


//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;


//declare calculator class
public class Calculator extends JFrame
 {
private String [] terms = {"5","7", "15", "30"};
private double [] rates = {0.05, 0.0535, 0.55, 0.0575};
private JLabel amountLabel = new JLabel ("Mortgage Amount:");
private JTextField amount = new JTextField();
private JLabel termLabel = new JLabel ("Term of Loan:");
private JTextField term = new JTextField();
private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
private JTextField rate = new JTextField();
private JComboBox termList = new JComboBox(terms);
private JCheckBox loadFile = new JCheckBox();
private JLabel payLabel = new JLabel("Monthly Payment:");
private JLabel payment = new JLabel();
private JButton calculate = new JButton("Calculate");
private JButton clear = new JButton("Clear");
private JButton exit = new JButton("Exit");
private JTextArea paymentSchedule = new JTextArea();
private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
private Container cp = getContentPane();

	public Calculator(String title)
	{
		super.setTitle(title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//handle term list
		termList.setSelectedIndex(0);
		termList.addActionListener(new ActionListener()		{
			public void actionPerformed(ActionEvent e){
				JComboBox cb = (JComboBox)e.getSource();
				String termYear = (String)cb.getSelectedItem();
				term.setText(termYear);
				int index = 0;
				switch (Integer.parseInt(termYear)){
					case 5: index = 0; break;
					case 7: index = 1; break;
					case 15: index = 2; break;
					case 30: index = 3; break;
				}
				rate.setText(rates[index] + "");
			}
		});





		//handle the button events
	calculate.addActionListener(new ActionListener(){

		public void actionPerformed(ActionEvent e){


			try{
				//calculate the payments.
				double p = Double.parseDouble(amount.getText());
				double r = Double.parseDouble(rate.getText()) / 12;
				double n = Integer.parseInt(term.getText()) * 12;
				double monthlyPayment = p * Math.pow (1 + r, n) * r / (Math.pow(1 + r, n)- 1);
				DecimalFormat df = new DecimalFormat("$###,###.00");
				payment.setText(df.format(monthlyPayment));


				//calculate the loan information

				double principal = p;
				int month;
				StringBuffer buffer = new StringBuffer();
				buffer.append("Month\tAmount\tInterest\tBalance\n");
				for (int i = 0; i < n; i++){
					month = i + 1;
					double interest = principal * r;
					double balance = principal + interest - monthlyPayment;
					buffer.append(month + "\t");
					buffer.append(new String(df.format(principal)) + "\t");
					buffer.append(new String(df.format(interest)) + "\t");
					buffer.append(new String(df.format(balance)) + "\n");
					principal = balance;

				}
				paymentSchedule.setText(buffer.toString());
			} catch (Exception ex) {
				System.out.println(ex);
			}
		}
	});
//handle file reader

loadFile.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent e){


		FileReader fr = new FileReader("term.txt");
		BufferedReader reader = new BufferedReader(fr);

		while(reader.readLine()) ! = null)
			{
			ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
			i++;
		}
		reader.close();
	}	});

	clear.addActionListener(new ActionListener(){

		public void actionPerformed(ActionEvent e){
			term.setText("");
			rate.setText("");
			amount.setText("");
			payment.setText("");
			paymentSchedule.setText("");
		}
	});


	exit.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			System.exit(1);
		}

	});

	JPanel calcScreen = new JPanel();
	calcScreen.setLayout(new GridLayout(10,4));
	calcScreen.add(amountLabel);
	calcScreen.add(amount);
	calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
	calcScreen.add(termList);
	calcScreen.add(termLabel);
	calcScreen.add(term);
	calcScreen.add(rateLabel);
	calcScreen.add(rate);
	calcScreen.add(new Label("Check Box to access rates from file"));
	calcScreen.add(loadFile);
	calcScreen.add(payLabel);
	calcScreen.add(payment);

	JPanel buttons = new JPanel();
	buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
	buttons.add(calculate);
	buttons.add(clear);
	buttons.add(exit);

	JPanel calc = new JPanel();
	calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
	calc.add(calcScreen);
	calc.add(buttons);
	cp.add(BorderLayout.NORTH, calc);
	cp.add(BorderLayout.CENTER, schedulePane);

	}

	public static void main(String[] args)
	{
		Calculator frame = new Calculator("Mortgage Calculator");
		frame.setSize(400,600);
		Frame.setVisible(true);


	}

}






I have attached the file I need to use with the code as well. One more question....should I put the file path in instead of just the filename?

example:
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src

instead of:
term.txt

Thank you again for your time and help with this. :helpsmilie:

Attached File(s)

  • Attached File  term.txt (27bytes)
    Number of downloads: 167

Was This Post Helpful? 0
  • +
  • -

#7 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 12:17 PM

You have an extra parentheses here:
while(reader.readLine()) ! = null)


At the end of readLine().
Was This Post Helpful? 0
  • +
  • -

#8 javadork  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 32
  • View blog
  • Posts: 135
  • Joined: 21-August 10

Re: Java mortgage calculator sequential file HELP...please

Posted 15 September 2010 - 12:35 PM

Also, you have a space between ! and = plus I notice that ratesLoadedArray and i are not defined anywhere.

		while(reader.readLine() != null)
			{
			ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
			i++;
		}


This post has been edited by Dogstopper: 15 September 2010 - 12:40 PM
Reason for edit:: fixed the errors.

Was This Post Helpful? 0
  • +
  • -

#9 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 08:59 AM

View Postjavadork, on 15 September 2010 - 11:35 AM, said:

Also, you have a space between ! and = plus I notice that ratesLoadedArray and i are not defined anywhere.

		while(reader.readLine() != null)
			{
			ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
			i++;
		}


That's my prblem, I do not understand how to define them, or even what I need to define to make this work. I am really frustrated with this because I pay so much money for my courses, then cant even get a helpful answer from my instructor. I have read and re-read my text, done numerous tutorials, and have even purchased additional books on Java, but I can not wrap my head around this. I only have 5 days left till this class ends and I just really need to learn how to convert the examples and suggestions to something that will work with my program. If I can just pass this class I will be happy. Thanks for your input I appreciate it. :boat:

This post has been edited by MrsE: 16 September 2010 - 09:00 AM

Was This Post Helpful? 0
  • +
  • -

#10 krizjaz  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 20
  • View blog
  • Posts: 99
  • Joined: 07-October 07

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 09:21 AM

I think, i here means index since index needs incrementation to store the values read from the text into the array separately:
FileReader fr = new FileReader("rates.txt");
BufferedReader reader = new BufferedReader(fr);
int index = 0;
while(reader.readLine() != null)
{
    ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
    index++;
}
                    
reader.close();


I would recommend you to use ArrayList or Vector if, for instance, you don't know how many rates are in the text file. Or, you could just read how many lines are in the text file and use it as the length for the array:
FileReader fr = new FileReader("rates.txt");
BufferedReader reader = new BufferedReader(fr);
int max = 0, index = 0;
while(reader.readLine() != null)
{
    max++;
}
reader.close();
Double[] ratesLoadedArray = new Double[max];
//then the continuation of the code. . .


Was This Post Helpful? 0
  • +
  • -

#11 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 09:28 AM

View Postkrizjaz, on 16 September 2010 - 08:21 AM, said:

I would recommend you to use ArrayList or Vector if, for instance, you don't know how many rates are in the text file. Or, you could just read how many lines are in the text file and use it as the length for the array:
FileReader fr = new FileReader("rates.txt");
BufferedReader reader = new BufferedReader(fr);
int max = 0, index = 0;
while(reader.readLine() != null)
{
    max++;
}
reader.close();
Double[] ratesLoadedArray = new Double[max];
//then the continuation of the code. . .


I think that is not good idea iterate twice over the same file. The first time just to know how many lines are in there and
the second for read them. But it is good idea use a ArrayList since you do not know how many lines are in there. Just declare
the ArrayList:
ArrayList<Double> ratesLoadedArray = new ArrayList<Double>();


And then inside the while loop store every double value in the array.
ratesLoadedArray.add(Double.parseDouble(reader.readLine()));


Was This Post Helpful? 0
  • +
  • -

#12 krizjaz  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 20
  • View blog
  • Posts: 99
  • Joined: 07-October 07

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 09:49 AM

Quote

I think that is not good idea iterate twice over the same file.

Yes, but i didn't finish the code. He could initialize again the FileReader and the BufferedReader.
//continuation of the code:
fr = new FileReader("rates.txt");
reader = new BufferedReader(fr);
Double[] ratesLoadedArray = new Double[max];
String str;
while((str = reader.readLine()) != null){
	ratesLoadedArray[index] = Double.parseDouble(str);
	index++;
}
reader.close();


Also, the line that was read in the text file should be stored because when you call again the readLine() method, it reads the next line. So, it means, it cuts the loop into half.
Example:
Inside the rates.txt file, we have:
1.0
1.1
1.2
1.3
in the code:
while(reader.readLine() != null){
        //on the first loop, readLine() method was called from the condition of the while loop and returns something and wasn't stored. The value in the text file is 1.0
        ratesLoadedArray[index] = Double.parseDouble(reader.readLine());
        //called again the readLine() method and it returned the next value. The next value is 1.1 and is now stored in the array.
        //and so on. .


So, the call of the readLine() method inside the while loop would not be stored. You should store the value returned by the method in a variable (mine, i stored in a string) and parse it so that it would be stored in the array of Double.

This post has been edited by krizjaz: 16 September 2010 - 10:10 AM

Was This Post Helpful? 0
  • +
  • -

#13 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 10:32 AM

Thanks. I am trying to get this to work, but I am still getting lots of errors..when I comment out the section where Iam trying to make the checkbox work, my GUI shows up with all the components. I can't believe I am having such a hard time with this.
Here is what I am trying to add to the working program to get the desired changes:
ArrayList<Double> ratesLoadedArray = new ArrayList<Double>();

and:
checkBox.addActionListener(new ActionListener(){

	public void actionPerformed(ActionEvent e){
		FileReader fr = new FileReader("term.text");
		BufferedReader reader = new BufferedReader(fr);
		int max = 0, index = 0;
		while(reader.readLine() != null){
			max++;
		}
ratesLoadedArray.add(Double.parseDouble(reader.readLine()));
	}
});




Here is my updated code:
/** Mortgage Calculator Program
 * Week 5 PRG421
 *Change request #7
 *Write the program in Java (with a graphical user interface) and have it
 * calculate and display the mortgage payment amount from user input of the
 * amount of the mortgage and the user's selection from a menu of available
 * mortgage loans:
 *
- 5 years at 5%
 - 7 years at 5.35%
 - 15 years at 5.5 %
 - 30 years at 5.75%

Use an array for the mortgage data for the different loans.
 Read the interest rates to fill the array from a sequential file.
  Display the mortgage payment amount followed by the loan balance and interest
   paid for each payment over the term of the loan. Add graphics in the form of a chart.
    Allow the user to loop back and enter a new amount and make a new selection or quit.
     Please insert comments in the program to document the program.
*
*Author: Stacey Estey
*Due September 20, 2010*/


//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;


//declare calculator class
public class Calculator extends JFrame
 {
private String [] terms = {"5","7", "15", "30"};
private double [] rates = {0.05, 0.0535, 0.55, 0.0575};
ArrayList<Double> ratesLoadedArray = new ArrayList<Double>();
private JLabel amountLabel = new JLabel ("Mortgage Amount:");
private JTextField amount = new JTextField();
private JLabel termLabel = new JLabel ("Term of Loan:");
private JTextField term = new JTextField();
private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
private JTextField rate = new JTextField();
private JComboBox termList = new JComboBox(terms);
private JCheckBox checkBox = new JCheckBox();
private JLabel payLabel = new JLabel("Monthly Payment:");
private JLabel payment = new JLabel();
private JButton calculate = new JButton("Calculate");
private JButton clear = new JButton("Clear");
private JButton exit = new JButton("Exit");
private JTextArea paymentSchedule = new JTextArea();
private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
private Container cp = getContentPane();

	public Calculator(String title)
	{
		super.setTitle(title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//handle term list
		termList.setSelectedIndex(0);
		termList.addActionListener(new ActionListener()		{
			public void actionPerformed(ActionEvent e){
				JComboBox cb = (JComboBox)e.getSource();
				String termYear = (String)cb.getSelectedItem();
				term.setText(termYear);
				int index = 0;
				switch (Integer.parseInt(termYear)){
					case 5: index = 0; break;
					case 7: index = 1; break;
					case 15: index = 2; break;
					case 30: index = 3; break;
				}
				rate.setText(rates[index] + "");
			}
		});





		//handle the button events
	calculate.addActionListener(new ActionListener(){

		public void actionPerformed(ActionEvent e){


			try{
				//calculate the payments.
				double p = Double.parseDouble(amount.getText());
				double r = Double.parseDouble(rate.getText()) / 12;
				double n = Integer.parseInt(term.getText()) * 12;
				double monthlyPayment = p * Math.pow (1 + r, n) * r / (Math.pow(1 + r, n)- 1);
				DecimalFormat df = new DecimalFormat("$###,###.00");
				payment.setText(df.format(monthlyPayment));


				//calculate the loan information

				double principal = p;
				int month;
				StringBuffer buffer = new StringBuffer();
				buffer.append("Month\tAmount\tInterest\tBalance\n");
				for (int i = 0; i < n; i++){
					month = i + 1;
					double interest = principal * r;
					double balance = principal + interest - monthlyPayment;
					buffer.append(month + "\t");
					buffer.append(new String(df.format(principal)) + "\t");
					buffer.append(new String(df.format(interest)) + "\t");
					buffer.append(new String(df.format(balance)) + "\n");
					principal = balance;

				}
				paymentSchedule.setText(buffer.toString());

			} catch (Exception ex) {
				System.out.println(ex);
			}
		}
	});

   checkBox.addActionListener(new ActionListener(){

	public void actionPerformed(ActionEvent e){
		FileReader fr = new FileReader("term.text");
		BufferedReader reader = new BufferedReader(fr);
		int max = 0, index = 0;
		while(reader.readLine() != null){
			max++;
		}
ratesLoadedArray.add(Double.parseDouble(reader.readLine()));
	}
});


	clear.addActionListener(new ActionListener(){

		public void actionPerformed(ActionEvent e){
			term.setText("");
			rate.setText("");
			amount.setText("");
			payment.setText("");
			paymentSchedule.setText("");
		}
	});


	exit.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			System.exit(1);
		}

	});

	JPanel calcScreen = new JPanel();
	calcScreen.setLayout(new GridLayout(15,20));
	calcScreen.add(amountLabel);
	calcScreen.add(amount);
	calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
	calcScreen.add(new Label("OR"));
	calcScreen.add(new Label("Check Box to access rates from file"));
	calcScreen.add(checkBox);
	calcScreen.add(termList);
	calcScreen.add(termLabel);
	calcScreen.add(term);
	calcScreen.add(rateLabel);
	calcScreen.add(rate);
	calcScreen.add(payLabel);
	calcScreen.add(payment);

	JPanel buttons = new JPanel();
	buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
	buttons.add(calculate);
	buttons.add(clear);
	buttons.add(exit);

	JPanel calc = new JPanel();
	calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
	calc.add(calcScreen);
	calc.add(buttons);
	cp.add(BorderLayout.NORTH, calc);
	cp.add(BorderLayout.CENTER, schedulePane);

	}

	public static void main(String[] args)
	{
		Calculator frame = new Calculator("Mortgage Calculator");
		frame.setSize(600,800);
		frame.setVisible(true);


	}

}


Here are the errors I am getting right now:

Quote

--------------------Configuration: <Default>--------------------
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:128: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader("term.text");
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:131: unreported exception java.io.IOException; must be caught or declared to be thrown
while(reader.readLine() != null){
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:134: unreported exception java.io.IOException; must be caught or declared to be thrown
ratesLoadedArray.add(Double.parseDouble(reader.readLine()));
^
3 errors

Process completed.


I know I sound desparate...lol...that's cuz I am. I am reviewing all the Java tutorials I can today and trying different things. I only have 4 entries in the text file, so I have to make it when the user selects 5 years from the combo box it reads and displays 0.05 from the text file. The sharks are gaining on me and my ship is sinking very quickly! :death:

Attached File(s)

  • Attached File  term.txt (27bytes)
    Number of downloads: 124

Was This Post Helpful? 0
  • +
  • -

#14 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 10:39 AM

For the first error. You need write the path to your term.text file. Something like:
FileReader fr = new FileReader("c:/csi/loandata.txt");


For the others two erros. You must sorround the lines between while(reader.readLine() != null) and ratesLoadedArray.add(Double.parseDouble(reader.readLine())) with a try/catch block.
Was This Post Helpful? 0
  • +
  • -

#15 krizjaz  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 20
  • View blog
  • Posts: 99
  • Joined: 07-October 07

Re: Java mortgage calculator sequential file HELP...please

Posted 16 September 2010 - 10:47 AM

Quote

checkBox.addActionListener(new ActionListener(){

	public void actionPerformed(ActionEvent e){
		FileReader fr = new FileReader("term.text");
		BufferedReader reader = new BufferedReader(fr);
		int max = 0, index = 0;
		while(reader.readLine() != null){
			max++;
		}
ratesLoadedArray.add(Double.parseDouble(reader.readLine()));
	}
});


No! If you use ArrayList, it automatically adds space. So, you shouldn't be including these:
int max = 0, index = 0;


And the while loop should be used for reading the values in the text file. And as i've said, store the values returned by the readLine() method first!:
String str;
while((str = reader.readLine()) != null){
	ratesLoadedArray.add(Double.parseDouble(str));
}



Ok, I thought you've already have knowledge on catching exceptions. Enclose the code with try and catch:
try{
	FileReader fr = new FileReader("term.text");
	BufferedReader reader = new BufferedReader(fr);
	while((str = reader.readLine()) != null){
		ratesLoadedArray.add(Double.parseDouble(str));
	}
	reader.close();
}catch(Exception ex){}


This post has been edited by krizjaz: 16 September 2010 - 11:04 AM

Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3