Reading from a file to fill an array

Reply

Join Date: Jul 2005
Posts: 6
Reputation: zoodaddy65 is an unknown quantity at this point 
Solved Threads: 0
zoodaddy65 zoodaddy65 is offline Offline
Newbie Poster

Reading from a file to fill an array

 
0
  #1
Jul 29th, 2005
Greetings all,
I am, obviously, new to Java. I am in my second Java class at UOP, and quite honestly, they seem to believe in letting us teach ourselves! Enough of my rant.
I am currently working on expanding a mortgage calculator program, such that it needs to open a .txt file (I assume), and fill an array with 'double' values to be used as interest rates. I currently have a .txt file named "rates.txt" residing in the same folder as my .java. What I have compiles just fine, but when it is executed, it returns "0.0" for all seven interest rates in the JComboBox. I am thinking that maybe I missed a line of code in the transfer of data, failed to open the file, or am just all messed up! One of my fellow students already pointed out that part of my problem is passing a String to a Double. I thought that when a .txt file was opened, it was read out as a String, then needed to be converted to Double. Hopefully someone can give me some guidance here. Not looking for give-me's, just some pointers.
Below is the portion of code that I intended to accomplish this transfer, let me know if you need more.
  1. public void mortCalc() {
  2. try {
  3. int j = 0;
  4. String temp = "";
  5. BufferedReader in = new BufferedReader(new FileReader("rate.txt"));
  6. while((temp = in.readLine()) != null) {
  7. rate[j] = Double.parseDouble(temp.trim());
  8. j++;
  9. }
  10. in.close();
  11. }
  12.  
  13. catch (Exception E) {
  14. }
Reply With Quote Quick reply to this message  
Join Date: Nov 2004
Posts: 6,144
Reputation: jwenting is just really nice jwenting is just really nice jwenting is just really nice jwenting is just really nice 
Solved Threads: 212
Team Colleague
jwenting's Avatar
jwenting jwenting is offline Offline
duckman

Re: Reading from a file to fill an array

 
0
  #2
Jul 30th, 2005
NEVER eat exceptions. At the very least log the exception message, better yet is to log the entire exception stacktrace.

My guess is that either your read operation fails, causing the method to abort, or the data you're reading cannot be parsed to a double (empty string maybe?).

Your "while (temp = in.readLine() != null)" also looks highly suspicious.
I'm not sure (I'd never write it like that) but possibly it fails to assign a value to temp, or assigns the string representation of the comparison instead of the data read from the file.
Don't use such statements, rather split them up.

Try
  1. String temp = in.readLine();
  2. while (temp != null) {
  3. // blah blah
  4. temp = readLine();
  5. }
instead.

And of course don't use variable names starting with a capital letter.
Use "catch (Exception e)", or better yet catch specific exceptions rather than a single blanket statement.
As people are clearly allowed to attack me but I'm not allowed to defend myself, I no longer post to this site.
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 6
Reputation: zoodaddy65 is an unknown quantity at this point 
Solved Threads: 0
zoodaddy65 zoodaddy65 is offline Offline
Newbie Poster

Re: Reading from a file to fill an array

 
0
  #3
Jul 30th, 2005
Thanks for the advice, jwenting. Another fellow I was talking to yesterday looked almost horrified when he saw my empty catch. I found a site last night that had explanations and suggestions very much like what you have here. I had to quit last night, since 5 am comes SOOO early. (Yea, I work weekends) I'll be playing with this some more this evening, I'll let you know how it works out.

Thanks a million for the info!
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 609
Reputation: freesoft_2000 is an unknown quantity at this point 
Solved Threads: 7
freesoft_2000 freesoft_2000 is offline Offline
Practically a Master Poster

Re: Reading from a file to fill an array

 
0
  #4
Jul 30th, 2005
Hi everyone,

I have something to confess, i have been eating exceptions since
Java 1.0. I know its a bad habit but i got used to it

Richard West
Microsoft uses "One World, One Web, One Program" as a slogan.
Doesn’t that sound like "Ein Volk, Ein Reich, Ein Führer" to you, too?
— Eric S. Raymond

Tell me what type of software do you like and what would you pay for it

http://www.daniweb.com/techtalkforums/thread19660.html
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: Reading from a file to fill an array

 
0
  #5
Jul 30th, 2005
I like to catch exceptions. I don't, however, throw some message up in the users face letting them know. I usually print something out to the console, and then deal with the error. lets say it's a calculator and the user entered a letter instead of a number...I would prefer to simply clear the text area, rather than throwing an error message up in the users face.
Reply With Quote Quick reply to this message  
Join Date: Nov 2004
Posts: 6,144
Reputation: jwenting is just really nice jwenting is just really nice jwenting is just really nice jwenting is just really nice 
Solved Threads: 212
Team Colleague
jwenting's Avatar
jwenting jwenting is offline Offline
duckman

Re: Reading from a file to fill an array

 
0
  #6
Jul 30th, 2005
Depending on the exception that might be good enough. But if the user can do something about the exception (say it's a network error or he typed something wrong causing a validation error) you should notify him instead of just logging it somewhere.

SOMETIMES eating an exception is justified, but in such cases you should always carefully document the exact reason you're eating it.
For example, in one of my projects an exception can occur in an XML read operation when an optional parameter to an XML element isn't there.
I know the read operation for that parameter may yield an exception if the parameter is absent but as the parameter is optional I don't care and I document that.
If other exceptions are thrown I take action accordingly (for example an invalid value for the parameter).
As people are clearly allowed to attack me but I'm not allowed to defend myself, I no longer post to this site.
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: Reading from a file to fill an array

 
0
  #7
Jul 30th, 2005
Is there a way to actually log the exceptions?? Not just for the one time the program is run, but for the whole life of the application??
Reply With Quote Quick reply to this message  
Join Date: Nov 2004
Posts: 6,144
Reputation: jwenting is just really nice jwenting is just really nice jwenting is just really nice jwenting is just really nice 
Solved Threads: 212
Team Colleague
jwenting's Avatar
jwenting jwenting is offline Offline
duckman

Re: Reading from a file to fill an array

 
0
  #8
Jul 31st, 2005
Sure. Since 1.4 Java has included a nice logging package which can log to just about anything.
You can log to the console (effectively what you're doing now but it includes origin and timestamps), to file, or even to a network connection (which could point to a program storing the information in a database for example).

Or use one of the many 3rd party logging packages available.
As people are clearly allowed to attack me but I'm not allowed to defend myself, I no longer post to this site.
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: Reading from a file to fill an array

 
0
  #9
Jul 31st, 2005
Thanks. I found it. I guess I should have googled first because it wasn't hard to find! It looks pretty sweet though. I'm not sure I understand the Level thing though, but I'll go through a tutorial soon I think.
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 6
Reputation: zoodaddy65 is an unknown quantity at this point 
Solved Threads: 0
zoodaddy65 zoodaddy65 is offline Offline
Newbie Poster

Re: Reading from a file to fill an array

 
0
  #10
Jul 31st, 2005
Greetings All,
I appreciate the suggestions I got with the previous post, greatly. Obviously I am working on homework, I admit this readily. I have spent about 6 hours a night for the last three nights searching tech sites and instructional sites, and it is really starting to prove to me just how much I have to learn. Would you mind looking at the code and giving me an idea of how many stupid things I am doing? It's burning me up that I cannot seem to figure this out, but I figured I'd rather ask for some assistance rather than ..... It compiles fine, but when you execute it, the interest JComboBox is unpopulated. I was also getting an IndexOutOfBounds exception, so I increased the size of String strRate[]. The file that is supposed to be read, "intRate.txt", consists of seven interest rates in the form of #.##. Each one is on it's own line.

  1. import java.awt.*;
  2. import javax.swing.*;
  3. import java.awt.event.*;
  4. import java.text.NumberFormat;
  5. import java.io.*;
  6. import java.lang.*;
  7.  
  8.  
  9. //sets up program variables
  10. public class MikesCalc extends JFrame implements ActionListener {
  11. NumberFormat money = NumberFormat.getCurrencyInstance();
  12. private JLabel title = new JLabel("Mortgage Calculator");
  13. private JFrame amortFrame;
  14. private JTextArea amort;
  15. private String amortTable;
  16. private JLabel prLabel = new JLabel("Loan Amount");
  17. private JTextField pr = new JTextField(10);
  18. private JButton calcButton = new JButton("Calculate");
  19. private JLabel payLabel = new JLabel("Monthly Payment");
  20. private JTextField payment = new JTextField(10);
  21. private int years[] = {7, 15, 30};
  22. private double rate[] = new double[30];
  23. private double intRate, term, loanAmount, monthlyPayment, intPayment;
  24. private JLabel rateLabel = new JLabel("Annual Interest Rate: choose or enter one");
  25. private String [] rateChoice = new String[50];
  26. private JComboBox rateBox = new JComboBox();
  27. private JLabel yearsLabel = new JLabel("Loan Term (in years): choose or enter one");
  28. private String [] yearsChoice = {years[0] + "", years[1] + "", years[2] + ""};
  29. private JComboBox yearsBox = new JComboBox(yearsChoice);
  30. private String strRate[] = new String[50];
  31.  
  32. //Creates the window
  33. public MikesCalc() {
  34. super("Mortgage Calculator");
  35. setSize(300, 200);
  36. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  37. setVisible(true);
  38.  
  39. //Creates the container
  40. Container con = getContentPane();
  41. FlowLayout fresh = new FlowLayout(FlowLayout.LEFT);
  42. con.setLayout(fresh);
  43.  
  44. //identifies the items that can trigger events
  45. calcButton.addActionListener(this);
  46. pr.addActionListener(this);
  47. yearsBox.addActionListener(this);
  48.  
  49. //fills out the container
  50. con.add(prLabel);
  51. con.add(pr);
  52. con.add(rateLabel);
  53. con.add(rateBox);
  54. rateBox.setEditable(true);
  55. con.add(yearsLabel);
  56. con.add(yearsBox);
  57. yearsBox.setEditable(true);
  58. con.add(calcButton);
  59. con.add(payLabel);
  60. con.add(payment);
  61. payment.setEditable(false);
  62. setContentPane(con);
  63.  
  64. }
  65.  
  66. //Calls the calculations once the events are recognized
  67. public void actionPerformed(ActionEvent event) {
  68. Object source = event.getSource();
  69. if(source == calcButton) {
  70. mortCalc();
  71. }
  72. }
  73.  
  74.  
  75.  
  76. //Does the calculations and exception handling
  77. public void mortCalc() {
  78.  
  79.  
  80.  
  81. try {
  82. int j = 0;
  83. BufferedReader in = new BufferedReader(new FileReader("intrate.txt"));
  84. String temp = "";
  85.  
  86. while((temp = in.readLine()) != null) {
  87. strRate[j] = temp;
  88. j++;
  89. }
  90.  
  91. in.close();
  92. }
  93.  
  94. catch (FileNotFoundException e) {
  95. System.out.println("Can't find file rate.txt!");
  96. return;
  97. }
  98.  
  99. catch (IndexOutOfBoundsException e) {
  100. System.out.println("Too many numbers in data field");
  101. System.out.println("Processing aborted");
  102. }
  103.  
  104. catch (IOException ioe) {
  105. System.out.println("IOException: " + ioe.getMessage());
  106. }
  107.  
  108. rate[0] = Double.parseDouble(strRate[0]);
  109. rate[1] = Double.parseDouble(strRate[1]);
  110. rate[2] = Double.parseDouble(strRate[2]);
  111. rate[3] = Double.parseDouble(strRate[3]);
  112. rate[4] = Double.parseDouble(strRate[4]);
  113. rate[5] = Double.parseDouble(strRate[5]);
  114. rate[6] = Double.parseDouble(strRate[6]);
  115. String [] rateChoice = {rate[0] + "", rate[1] + "", rate[2] + "", rate[3] + "", rate[4] + "", rate[5] + "", rate[6] + ""};
  116. rateBox = new JComboBox(rateChoice);
  117. rateBox.addActionListener(new MikesCalc());
  118.  
  119.  
  120. try {
  121. double loanAmount = Double.parseDouble(pr.getText());
  122. }
  123.  
  124. catch (NumberFormatException e) {
  125. JOptionPane.showMessageDialog(null, "Invalid Loan Amount entry, please enter a number", "Error", JOptionPane.PLAIN_MESSAGE);
  126. payment.setText(null);
  127. pr.setText(null);
  128.  
  129. }
  130.  
  131. try {
  132. double intRate = Double.parseDouble((String) rateBox.getSelectedItem());
  133. }
  134.  
  135. catch (NumberFormatException e) {
  136. JOptionPane.showMessageDialog(null, "Invalid Interest Rate entry, please enter a percentage", "Error", JOptionPane.PLAIN_MESSAGE);
  137. payment.setText(null);
  138. pr.setText(null);
  139. }
  140.  
  141. try {
  142. double term = Double.parseDouble((String) yearsBox.getSelectedItem());
  143. }
  144.  
  145. catch (NumberFormatException e) {
  146. JOptionPane.showMessageDialog(null, "Invalid Term entry, please enter a number", "Error", JOptionPane.PLAIN_MESSAGE);
  147. payment.setText(null);
  148. pr.setText(null);
  149. }
  150.  
  151.  
  152. double loanAmount = Double.parseDouble(pr.getText());
  153. double intRate = Double.parseDouble((String) rateBox.getSelectedItem());
  154. double term = Double.parseDouble((String) yearsBox.getSelectedItem());
  155. double monthlyInt = (intRate / 100) / 12;
  156. double totalMonths = term * 12;
  157. double monthlyPayment = (loanAmount * monthlyInt)
  158. / (1 - Math.pow(1/ (1 + monthlyInt), term * 12));
  159. String showPayment = money.format(monthlyPayment);
  160. payment.setText(showPayment);
  161.  
  162.  
  163. amortFrame = new JFrame();
  164. Container con = amortFrame.getContentPane();
  165. amort = new JTextArea("");
  166.  
  167. amortTable = ("\tPrincipal Paid\t\tInterest Paid\t\tNew Balance\n");
  168. amort.append(amortTable);
  169. double intPayment = loanAmount * ((intRate / 100) / 12);
  170. term = term * 12;
  171. //starts amortization loop
  172. while (term > 0) {
  173.  
  174. //performs the computations for the amortization
  175. double prPayment = monthlyPayment - intPayment;
  176. double bal = loanAmount - prPayment;
  177. amortTable = ("\t" + money.format(prPayment) + "\t\t" + money.format(intPayment) + "\t\t" + money.format(bal) + "\n");
  178. amort.append(amortTable);
  179. loanAmount = bal;
  180. intPayment = bal * ((intRate / 100) /12);
  181. term--;
  182. }
  183.  
  184. //sets up amortization window
  185. amortFrame.setTitle("Mortgage Amortization");
  186. con.add(amort, BorderLayout.SOUTH);
  187. con.add(new JScrollPane(amort), BorderLayout.CENTER);
  188. amortFrame.setSize(600, 500);
  189. amortFrame.setVisible(true);
  190. }
  191.  
  192. public static void main(String args[]) {
  193.  
  194. MikesCalc app = new MikesCalc();
  195.  
  196. }
  197. }
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC