# Create a sequential File

Page 1 of 1

## 7 Replies - 17030 Views - Last Post: 02 February 2009 - 02:30 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=83021&amp;s=358833c4a3271b7c774296923d1fab27&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 DjengoMac

Reputation: 0
• Posts: 5
• Joined: 27-January 09

# Create a sequential File

Posted 27 January 2009 - 01:38 AM

[size=7][size=5]

```/*
MortgagePaymentCalc
PRG421 - Java Programming II

Formulae:	 P - Principal
I - Interest Rate
M - Number of Months
X - Monthly Payment

X = P[(I/12)(1+I/12)^(M)]/[(1+(I/12))^(M)-1]

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:

- 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.

*/

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

public class MortgagePaymentCalc extends JFrame implements ActionListener {

DecimalFormat calcPattern = new DecimalFormat("0.00");	//Makes it a little bit easier just in case a Deciaml is Entered

JLabel loanAmountLabel = new JLabel("Loan Amount (Without \$):");
JTextField loanAmountText = new JTextField(10);
JButton calculateButton = new JButton("Calculate Payment");
JTextField paymentText = new JTextField(10);
JLabel monthlyPaymentLabel = new JLabel("");
String[] mortgageStrings = { "Select terms", "7years; 5.35%", "15years; 5.5%", "30years; 5.75%" };
JComboBox mortgageList = new JComboBox(mortgageStrings);
JButton clearButton = new JButton("Clear");
JButton quitButton = new JButton("Quit");

// Creates a text box to display all the info

JTextArea textArea = new JTextArea(30, 25);
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

// Variable setting for interest rate and the length of loan

String loanLength, interestRate;

public MortgagePaymentCalc() {

super("McBride Financial Services Mortgage Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
pane.setLayout(fl);
mortgageList.setSelectedIndex(0);		// set first entry combo box for the default selected

//Should anyone be like me, this allows the Calculate button to be pushed by hitting "Enter"...

getRootPane().setDefaultButton(calculateButton);
setContentPane(pane);

//Gives Functionality to the buttons...

}

public static void main(String args[]) {

//Sets the Variables for the Frame (Size, Resizable, and what not)...

JFrame aFrame = new MortgagePaymentCalc();
aFrame.setTitle("McBride Financial Services Mortgage Calculator");
aFrame.setSize(310,650);

aFrame.setResizable(true);
aFrame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {

//Identifies the "what to do" when the "Button" is Clicked...

Object clickSource = e.getSource();

// set variables when specific mortgage terms are selected (e.g. "7yr; 5.35pt", "15yr; 5.5pt", "30yr; 5.75pt")

if (clickSource == mortgageList) {

// Gathers the selected terms

String terms = (String)mortgageList.getSelectedItem();

// Forces a choice

if (!terms.startsWith("Select")) {

// Gathers the loan length in years

int yearIndex = terms.indexOf("years");
loanLength = terms.substring(0,yearIndex);

// Gathers the  interest rate

int startPercentageIndex = terms.indexOf("; ");
int endPercentageIndex = terms.indexOf("%");
interestRate = terms.substring(startPercentageIndex + 2, endPercentageIndex);
}
}

//This runs the Calculation on the Formulae when asked to...

if (clickSource == calculateButton) {

//clear the text area before each calculation
textArea.setText("");

String loanAmount = loanAmountText.getText();
String interestrate = interestRate;
String years = loanLength;

//The Formulae

double total = Double.parseDouble(loanAmount) * (((((Double.parseDouble(interestrate)) / 100) / 12) * (Math.pow(1 + (((Double.parseDouble(interestrate)) / 100) / 12), Integer.parseInt(years) * 12))) / ((Math.pow(1 + (((Double.parseDouble(interestrate)) / 100) / 12), Integer.parseInt(years) * 12)) - 1));

//Display for the Monthly Payment

paymentText.setText("\$" + calcPattern.format(total));

//Calculates the monthly interest

double monthlyInterest = Double.parseDouble(loanAmount) / (12 * 100);
double currentMonthlyInterest = Double.parseDouble(loanAmount) * (Double.parseDouble(interestrate) / (12 * 100));
double monthlyPayment = total - currentMonthlyInterest;
double newBalance = Double.parseDouble(loanAmount) - monthlyPayment;
int monthNumber = 1;
textArea.append("Month" + "\tBalance" + "\tInterest\n");

// Keeps looping until the formulae is at a 0 balance

while (newBalance > 0) {

// Displays the Month

textArea.append(monthNumber + "\t" + calcPattern.format(newBalance) + "\t" + calcPattern.format(currentMonthlyInterest) + "\n");

currentMonthlyInterest = newBalance * (Double.parseDouble(interestrate) / (12 * 100));
monthlyPayment = total - currentMonthlyInterest;
newBalance = newBalance - monthlyPayment;
monthNumber++;

}

}

//This gives the User the Choice to either Re-Enter the Variables or "Clear" it all out altogether.

if (clickSource == clearButton) {
loanAmountText.setText("");
paymentText.setText("");
loanAmountText.requestFocus();
}

//If you can't stand the Heat, get out of the Kithcen...That means you can Quit

if (clickSource == quitButton) {
System.exit(0);
}
}
}

```

Sure you've all seen this a million times. The Uop kids looking for answers. Well programming is not my thing, I do multimedia and this is far from. My question is how do I go about starting a Sequential file. i tried googling and looking at the e-book resource and I see a lot of information, but never "do this to start". I'm not looking for an end solution here. I saw this in my ebook, but I don't see an explanation of how this "gets" from one file to another.

```output = new DataOutputStream(new FileOutputStream(filename));

```

I'm already past my deadline, but that's the life of the ignorant I suppose. Any help would be great...thnx.

Is This A Good Question/Topic? 0

## Replies To: Create a sequential File

### #2 Gloin

• Expert Schmexpert...

Reputation: 235
• Posts: 4,489
• Joined: 04-August 08

## Re: Create a sequential File

Posted 27 January 2009 - 03:38 AM

```public static void SaveFile(int[] P, String fileName) throws IOException {

File F = new File(fileName);
FileOutputStream out;
try {
out = new FileOutputStream(F);
for (int i = 0; i < P.length; i++) {
out.write(P[i]);
}
out.close();
}
catch (Exception e) {
System.err.println ("Error writing to file");
}
}

```

This method takes an array of (int) values and a filename (String) as arguments and puts the values in a file. You can easily change the method to take different values.

### #3 DjengoMac

Reputation: 0
• Posts: 5
• Joined: 27-January 09

## Re: Create a sequential File

Posted 27 January 2009 - 12:01 PM

This is where I want to store the data to be "accessed" from another file?

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

```

And this is the code that "accesses" the other file, right?

```output = new DataOutputStream(new FileOutputStream(newFilename));

```

Or did I do that backwards?

I feel like I'm at the airport saying "well I'm arriving at the airport but I'm departing later, So am I an arrival or a departure". Vocabulary of the subject I'm working in always gave me the hardest time.

### #4 Gloin

• Expert Schmexpert...

Reputation: 235
• Posts: 4,489
• Joined: 04-August 08

## Re: Create a sequential File

Posted 27 January 2009 - 03:11 PM

input = reading from a file
output = writing to a file

So you're correct in your assumptions.

### #5 DjengoMac

Reputation: 0
• Posts: 5
• Joined: 27-January 09

## Re: Create a sequential File

Posted 27 January 2009 - 03:40 PM

KK, slowly but surely I'm getting this.

Working on implementing the "output" of an interest selection that is stored with one file. So that the Main Calc file can "input" it.

Combining the...

```output = new DataOutputStream(new FileOutputStream(newFilename))

```

With the...

```String[] mortgageStrings = { "Select terms", "7years; 5.35%", "15years; 5.5%", "30years; 5.75%" };
JComboBox mortgageList = new JComboBox(mortgageStrings);

```

To replace the one that's in...

```	import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import java.util.*;

public class MortgagePaymentCalc extends JFrame implements ActionListener {
private ObjectOutputStream output;

DecimalFormat calcPattern = new DecimalFormat("0.00");	//Makes it a little bit easier just in case a Deciaml is Entered

JLabel loanAmountLabel = new JLabel("Loan Amount (Without \$):");
JTextField loanAmountText = new JTextField(10);
JButton calculateButton = new JButton("Calculate Payment");
JTextField paymentText = new JTextField(10);
JLabel monthlyPaymentLabel = new JLabel("");
String[] mortgageStrings = { "Select terms", "7years; 5.35%", "15years; 5.5%", "30years; 5.75%" };
JComboBox mortgageList = new JComboBox(mortgageStrings);
JButton clearButton = new JButton("Clear");
JButton quitButton = new JButton("Quit");

// Creates a text box to display all the info

JTextArea textArea = new JTextArea(30, 25);
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

// Variable setting for interest rate and the length of loan

String loanLength, interestRate;

public MortgagePaymentCalc() {

super("McBride Financial Services Mortgage Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
pane.setLayout(fl);
mortgageList.setSelectedIndex(0);		// set first entry combo box for the default selected

//Should anyone be like me, this allows the Calculate button to be pushed by hitting "Enter"...

getRootPane().setDefaultButton(calculateButton);
setContentPane(pane);

//Gives Functionality to the buttons...

}

public static void main(String args[]) {

//Sets the Variables for the Frame (Size, Resizable, and what not)...

JFrame aFrame = new MortgagePaymentCalc();
aFrame.setTitle("McBride Financial Services Mortgage Calculator");
aFrame.setSize(310,650);
aFrame.setResizable(true);
aFrame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {

//Identifies the "what to do" when the "Button" is Clicked...

Object clickSource = e.getSource();

// set variables when specific mortgage terms are selected (e.g. "7yr; 5.35pt", "15yr; 5.5pt", "30yr; 5.75pt")

if (clickSource == mortgageList) {

// Gathers the selected terms

String terms = (String)mortgageList.getSelectedItem();

// Forces a choice

if (!terms.startsWith("Select")) {

// Gathers the loan length in years

int yearIndex = terms.indexOf("years");
loanLength = terms.substring(0,yearIndex);

// Gathers the  interest rate

int startPercentageIndex = terms.indexOf("; ");
int endPercentageIndex = terms.indexOf("%");
interestRate = terms.substring(startPercentageIndex + 2, endPercentageIndex);
}
}

//This runs the Calculation on the Formulae when asked to...

if (clickSource == calculateButton) {

//clear the text area before each calculation
textArea.setText("");

String loanAmount = loanAmountText.getText();
String interestrate = interestRate;
String years = loanLength;

//The Formulae

double total = Double.parseDouble(loanAmount) * (((((Double.parseDouble(interestrate)) / 100) / 12) * (Math.pow(1 + (((Double.parseDouble(interestrate)) / 100) / 12), Integer.parseInt(years) * 12))) / ((Math.pow(1 + (((Double.parseDouble(interestrate)) / 100) / 12), Integer.parseInt(years) * 12)) - 1));

//Display for the Monthly Payment

paymentText.setText("\$" + calcPattern.format(total));

//Calculates the monthly interest

double monthlyInterest = Double.parseDouble(loanAmount) / (12 * 100);
double currentMonthlyInterest = Double.parseDouble(loanAmount) * (Double.parseDouble(interestrate) / (12 * 100));
double monthlyPayment = total - currentMonthlyInterest;
double newBalance = Double.parseDouble(loanAmount) - monthlyPayment;
int monthNumber = 1;
textArea.append("Month" + "\tBalance" + "\tInterest\n");

// Keeps looping until the formulae is at a 0 balance

while (newBalance > 0) {

// Displays the Month

textArea.append(monthNumber + "\t" + calcPattern.format(newBalance) + "\t" + calcPattern.format(currentMonthlyInterest) + "\n");

currentMonthlyInterest = newBalance * (Double.parseDouble(interestrate) / (12 * 100));
monthlyPayment = total - currentMonthlyInterest;
newBalance = newBalance - monthlyPayment;
monthNumber++;

}

}

//This gives the User the Choice to either Re-Enter the Variables or "Clear" it all out altogether.

if (clickSource == clearButton) {
loanAmountText.setText("");
paymentText.setText("");
loanAmountText.requestFocus();
}

//If you can't stand the Heat, get out of the Kithcen...That means you can Quit

if (clickSource == quitButton) {
System.exit(0);
}
}
}

```

Thanks for the help Gloin.

### #6 Gloin

• Expert Schmexpert...

Reputation: 235
• Posts: 4,489
• Joined: 04-August 08

## Re: Create a sequential File

Posted 27 January 2009 - 03:41 PM

no problemo!

### #7 DjengoMac

Reputation: 0
• Posts: 5
• Joined: 27-January 09

## Re: Create a sequential File

Posted 27 January 2009 - 05:37 PM

Well I think I'm real close.

```	import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import java.util.*;

public class MortgagePaymentCalc extends JFrame implements ActionListener {

private FileOutputStream output;

DecimalFormat calcPattern = new DecimalFormat("0.00");	//Makes it a little bit easier just in case a Deciaml is Entered

JLabel loanAmountLabel = new JLabel("Loan Amount (Without \$):");
JTextField loanAmountText = new JTextField(10);
JButton calculateButton = new JButton("Calculate Payment");
JTextField paymentText = new JTextField(10);
JLabel monthlyPaymentLabel = new JLabel("");
JButton chooseButton = new JButton("Choose Term");
JButton clearButton = new JButton("Clear");
JButton quitButton = new JButton("Quit");

// Creates a text box to display all the info

JTextArea textArea = new JTextArea(30, 25);
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

// Variable setting for interest rate and the length of loan

String loanLength, interestRate, terms;

public MortgagePaymentCalc() {

super("McBride Financial Services Mortgage Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
pane.setLayout(fl);

//Should anyone be like me, this allows the Calculate button to be pushed by hitting "Enter"...

getRootPane().setDefaultButton(calculateButton);
setContentPane(pane);

//Gives Functionality to the buttons...

}

public static void main(String args[]) {

//Sets the Variables for the Frame (Size, Resizable, and what not)...

JFrame aFrame = new MortgagePaymentCalc();
aFrame.setTitle("McBride Financial Services Mortgage Calculator");
aFrame.setSize(310,650);
aFrame.setResizable(true);
aFrame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {

//Identifies the "what to do" when the "Button" is Clicked...

Object clickSource = e.getSource();

// set variables when specific mortgage terms are selected (e.g. "7yr; 5.35pt", "15yr; 5.5pt", "30yr; 5.75pt")

if (clickSource == chooseButton) {

// Gathers the Data from the Sequential File

output = new FileOutputStream(new FileOutputStream(terms));

// Forces a choice

if (!terms.startsWith("Select")) {

// Gathers the loan length in years

int yearIndex = terms.indexOf("years");
loanLength = terms.substring(0,yearIndex);

// Gathers the  interest rate

int startPercentageIndex = terms.indexOf("; ");
int endPercentageIndex = terms.indexOf("%");
interestRate = terms.substring(startPercentageIndex + 2, endPercentageIndex);
}
}

//This runs the Calculation on the Formulae when asked to...

if (clickSource == calculateButton) {

//clear the text area before each calculation
textArea.setText("");

String loanAmount = loanAmountText.getText();
String interestrate = interestRate;
String years = loanLength;

//The Formulae

double total = Double.parseDouble(loanAmount) * (((((Double.parseDouble(interestrate)) / 100) / 12) * (Math.pow(1 + (((Double.parseDouble(interestrate)) / 100) / 12), Integer.parseInt(years) * 12))) / ((Math.pow(1 + (((Double.parseDouble(interestrate)) / 100) / 12), Integer.parseInt(years) * 12)) - 1));

//Display for the Monthly Payment

paymentText.setText("\$" + calcPattern.format(total));

//Calculates the monthly interest

double monthlyInterest = Double.parseDouble(loanAmount) / (12 * 100);
double currentMonthlyInterest = Double.parseDouble(loanAmount) * (Double.parseDouble(interestrate) / (12 * 100));
double monthlyPayment = total - currentMonthlyInterest;
double newBalance = Double.parseDouble(loanAmount) - monthlyPayment;
int monthNumber = 1;
textArea.append("Month" + "\tBalance" + "\tInterest\n");

// Keeps looping until the formulae is at a 0 balance

while (newBalance > 0) {

// Displays the Month

textArea.append(monthNumber + "\t" + calcPattern.format(newBalance) + "\t" + calcPattern.format(currentMonthlyInterest) + "\n");

currentMonthlyInterest = newBalance * (Double.parseDouble(interestrate) / (12 * 100));
monthlyPayment = total - currentMonthlyInterest;
newBalance = newBalance - monthlyPayment;
monthNumber++;

}

}

//This gives the User the Choice to either Re-Enter the Variables or "Clear" it all out altogether.

if (clickSource == clearButton) {
loanAmountText.setText("");
paymentText.setText("");
loanAmountText.requestFocus();
}

//If you can't stand the Heat, get out of the Kithcen...That means you can Quit

if (clickSource == quitButton) {
System.exit(0);
}
}
}

```

```	import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import java.util.*;

public class InterestFile extends JFrame implements ActionListener {

private FileInputStream input;

String[] mortgageStrings = { "Select terms", "7years; 5.35%", "15years; 5.5%", "30years; 5.75%" };
JComboBox mortgageList = new JComboBox(mortgageStrings);
JButton submitButton = new JButton("Submit");

// Creates a text box to display all the info

JTextArea textArea = new JTextArea(30, 25);
JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

// Variable setting for interest rate and the length of loan

String loanLength, interestRate, filename;

public InterestFile() {

super("McBride Financial Services Mortgage Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
pane.setLayout(fl);
mortgageList.setSelectedIndex(0);		// set first entry combo box for the default selected

//Should anyone be like me, this allows the Calculate button to be pushed by hitting "Enter"...

setContentPane(pane);

//Gives Functionality to the buttons...

}

public static void main(String args[]) {

//Sets the Variables for the Frame (Size, Resizable, and what not)...

JFrame aFrame = new InterestFile();
aFrame.setTitle("McBride Financial Services Mortgage Calculator");
aFrame.setSize(310,650);
aFrame.setResizable(true);
aFrame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {

//Identifies the "what to do" when the "Button" is Clicked...

Object clickSource = e.getSource();

// set variables when specific mortgage terms are selected (e.g. "7yr; 5.35pt", "15yr; 5.5pt", "30yr; 5.75pt")

if (clickSource == mortgageList) {

// Gathers the selected terms

String terms = (String)mortgageList.getSelectedItem();

// Forces a choice

if (!terms.startsWith("Select")) {

// Gathers the loan length in years

int yearIndex = terms.indexOf("years");
loanLength = terms.substring(0,yearIndex);

// Gathers the  interest rate

int startPercentageIndex = terms.indexOf("; ");
int endPercentageIndex = terms.indexOf("%");
interestRate = terms.substring(startPercentageIndex + 2, endPercentageIndex);

}
if (clickSource == submitButton) {
input = new FileInputStream(new FileInputStream(terms));
System.exit(0);
}

}
}
}

```

I think my placement is wrong. I changed the "filename" to "terms", just cause. Neither can find symbol - constructor. What does that mean i need to fix? If this were HTML I would be done. Is it at least looking better?

### #8 DjengoMac

Reputation: 0
• Posts: 5
• Joined: 27-January 09

## Re: Create a sequential File

Posted 02 February 2009 - 02:30 AM

Unfortunately, I never got it to fully work. I did however get a B in the class and thank Gloin for all his help. It was much appreciated when nobody else would respond.