| | |
Reading from a file to fill an array
![]() |
•
•
Join Date: Jul 2005
Posts: 6
Reputation:
Solved Threads: 0
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.
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.
Java Syntax (Toggle Plain Text)
public void mortCalc() { try { int j = 0; String temp = ""; BufferedReader in = new BufferedReader(new FileReader("rate.txt")); while((temp = in.readLine()) != null) { rate[j] = Double.parseDouble(temp.trim()); j++; } in.close(); } catch (Exception E) { }
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
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.
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
Java Syntax (Toggle Plain Text)
String temp = in.readLine(); while (temp != null) { // blah blah temp = readLine(); }
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.
•
•
Join Date: Jul 2005
Posts: 6
Reputation:
Solved Threads: 0
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!
Thanks a million for the info!
•
•
Join Date: Jun 2004
Posts: 609
Reputation:
Solved Threads: 7
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
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
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
•
•
Join Date: Jun 2004
Posts: 2,108
Reputation:
Solved Threads: 18
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.
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).
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.
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.
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.
•
•
Join Date: Jul 2005
Posts: 6
Reputation:
Solved Threads: 0
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.
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.
Java Syntax (Toggle Plain Text)
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.text.NumberFormat; import java.io.*; import java.lang.*; //sets up program variables public class MikesCalc extends JFrame implements ActionListener { NumberFormat money = NumberFormat.getCurrencyInstance(); private JLabel title = new JLabel("Mortgage Calculator"); private JFrame amortFrame; private JTextArea amort; private String amortTable; private JLabel prLabel = new JLabel("Loan Amount"); private JTextField pr = new JTextField(10); private JButton calcButton = new JButton("Calculate"); private JLabel payLabel = new JLabel("Monthly Payment"); private JTextField payment = new JTextField(10); private int years[] = {7, 15, 30}; private double rate[] = new double[30]; private double intRate, term, loanAmount, monthlyPayment, intPayment; private JLabel rateLabel = new JLabel("Annual Interest Rate: choose or enter one"); private String [] rateChoice = new String[50]; private JComboBox rateBox = new JComboBox(); private JLabel yearsLabel = new JLabel("Loan Term (in years): choose or enter one"); private String [] yearsChoice = {years[0] + "", years[1] + "", years[2] + ""}; private JComboBox yearsBox = new JComboBox(yearsChoice); private String strRate[] = new String[50]; //Creates the window public MikesCalc() { super("Mortgage Calculator"); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); //Creates the container Container con = getContentPane(); FlowLayout fresh = new FlowLayout(FlowLayout.LEFT); con.setLayout(fresh); //identifies the items that can trigger events calcButton.addActionListener(this); pr.addActionListener(this); yearsBox.addActionListener(this); //fills out the container con.add(prLabel); con.add(pr); con.add(rateLabel); con.add(rateBox); rateBox.setEditable(true); con.add(yearsLabel); con.add(yearsBox); yearsBox.setEditable(true); con.add(calcButton); con.add(payLabel); con.add(payment); payment.setEditable(false); setContentPane(con); } //Calls the calculations once the events are recognized public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source == calcButton) { mortCalc(); } } //Does the calculations and exception handling public void mortCalc() { try { int j = 0; BufferedReader in = new BufferedReader(new FileReader("intrate.txt")); String temp = ""; while((temp = in.readLine()) != null) { strRate[j] = temp; j++; } in.close(); } catch (FileNotFoundException e) { System.out.println("Can't find file rate.txt!"); return; } catch (IndexOutOfBoundsException e) { System.out.println("Too many numbers in data field"); System.out.println("Processing aborted"); } catch (IOException ioe) { System.out.println("IOException: " + ioe.getMessage()); } rate[0] = Double.parseDouble(strRate[0]); rate[1] = Double.parseDouble(strRate[1]); rate[2] = Double.parseDouble(strRate[2]); rate[3] = Double.parseDouble(strRate[3]); rate[4] = Double.parseDouble(strRate[4]); rate[5] = Double.parseDouble(strRate[5]); rate[6] = Double.parseDouble(strRate[6]); String [] rateChoice = {rate[0] + "", rate[1] + "", rate[2] + "", rate[3] + "", rate[4] + "", rate[5] + "", rate[6] + ""}; rateBox = new JComboBox(rateChoice); rateBox.addActionListener(new MikesCalc()); try { double loanAmount = Double.parseDouble(pr.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid Loan Amount entry, please enter a number", "Error", JOptionPane.PLAIN_MESSAGE); payment.setText(null); pr.setText(null); } try { double intRate = Double.parseDouble((String) rateBox.getSelectedItem()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid Interest Rate entry, please enter a percentage", "Error", JOptionPane.PLAIN_MESSAGE); payment.setText(null); pr.setText(null); } try { double term = Double.parseDouble((String) yearsBox.getSelectedItem()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid Term entry, please enter a number", "Error", JOptionPane.PLAIN_MESSAGE); payment.setText(null); pr.setText(null); } double loanAmount = Double.parseDouble(pr.getText()); double intRate = Double.parseDouble((String) rateBox.getSelectedItem()); double term = Double.parseDouble((String) yearsBox.getSelectedItem()); double monthlyInt = (intRate / 100) / 12; double totalMonths = term * 12; double monthlyPayment = (loanAmount * monthlyInt) / (1 - Math.pow(1/ (1 + monthlyInt), term * 12)); String showPayment = money.format(monthlyPayment); payment.setText(showPayment); amortFrame = new JFrame(); Container con = amortFrame.getContentPane(); amort = new JTextArea(""); amortTable = ("\tPrincipal Paid\t\tInterest Paid\t\tNew Balance\n"); amort.append(amortTable); double intPayment = loanAmount * ((intRate / 100) / 12); term = term * 12; //starts amortization loop while (term > 0) { //performs the computations for the amortization double prPayment = monthlyPayment - intPayment; double bal = loanAmount - prPayment; amortTable = ("\t" + money.format(prPayment) + "\t\t" + money.format(intPayment) + "\t\t" + money.format(bal) + "\n"); amort.append(amortTable); loanAmount = bal; intPayment = bal * ((intRate / 100) /12); term--; } //sets up amortization window amortFrame.setTitle("Mortgage Amortization"); con.add(amort, BorderLayout.SOUTH); con.add(new JScrollPane(amort), BorderLayout.CENTER); amortFrame.setSize(600, 500); amortFrame.setVisible(true); } public static void main(String args[]) { MikesCalc app = new MikesCalc(); } }
![]() |
Similar Threads
- RE: reading .wav file and putting ito inot the array (C)
- reading txt file into array (C++)
- URGENT - Reading from txt file into a 2 dimension array (Java)
Other Threads in the Java Forum
- Previous Thread: Java GUI JOptionPane.showMessageDialog
- Next Thread: A newbie needs help in Java ......
| Thread Tools | Search this Thread |
-xlint add android api applet application applications array arrays automation bank bi binary blackberry bluetooth chat class clear client code compile compiler component database development dice digit eclipse equation error event formatingtextintooltipjava fractal freeze functiontesting game gameprogramming givemetehcodez graphics gui health html hyper ide idea image infinite int integer j2me java javame javaprojects jetbrains jni jpanel jtable julia learningresources linux list login main map method methods mobile myregfun netbeans nonstatic notdisplaying openjavafx pearl problem program project qt recursion scanner screen scrollbar server set sms sort sorting spamblocker sql sqlserver storm string superclass swing system thread threads tree variablebinding windows xor






