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.

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

String temp = in.readLine();
while (temp != null) {
  // blah blah
  temp = readLine();
}

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.

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!

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

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

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.

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.

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.

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();

	}
}

Just wanted to give you all who offered some advice a little update. I never fully got this to work, but I did find some problems with the last thing I posted.
I changed the file that I was reading from to a .dat, cause one of my classmates suggested that our SDK (version 1.5, I think?) did not like .txt files. I do not know how true this is, have not managed to confirm or disprove this theory. I moved the file reading code out of the "MortCalc()" method, since that was not allowing the file read to occur until that method was called. I put it into the end of the MikesCalc() method. I put in a System.out.println temporarily, just to verify that both of my arrays were receiving the information. That part works. I also got rid of one of the array initializations under the class, and put it in the method that was using it.
I ran out of time for the assignment, so I had to turn it in as is. I still want to figure this out, though. Another person suggested that I was initializing one of my arrays in such a way that it was causing it to fill the JComboBox with an empty string. This may be the case, but I do not know how to fix it. If anyone is interested in providing a few more pointers, I will provide any info they want. Thanks for your time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.