Hi, I need to do a file read and extract all the numbers in the text file to be used in my java program. However, I'm having some problem with the try and catch statement. Must the try and catch statement be in the main loop only? Can't I used it in a normal class?

Member Avatar

The try-catch statement must enclose all statements where an exception could be thrown. Could you list your code, if you're getting errors?

class Blosum50 extends Substitution

  private String residues = MatchApplet.display1;
  private String residues2 = MatchApplet.display2;

  public String getResidues()
  { return residues; }

  public String getResidues2()
  { return residues2; }

  [B]private double[][] residuescores =


  public Blosum50()
  { buildscore(residues, residues2, residuescores); }

I need to put the try and catch at the bold parts.

Member Avatar

Why exactly do you need a try catch there?

A try block, like any other block, has to occur within some sort of method. You can't put it out in the field declarations. Sorry.

It looks like you're trying to protect the assignment to that 2D array - have you been getting an exception there?

Member Avatar

Yes. What exception are you trying to prevent though? You may not need the block at all.

Yes. That means you'll have to do the assignment in a method. You can declare the array:

private double[][] residuescores;

will not throw any exceptions, and if you put it where you have it now, it'll be a class-level field, which means it'll be visible to all of the methods in that class.

Actually, I want to use the try and catch to read a text file, then equate the 2D array to whatever that is in the text file.

Okay - you mean you want to do something like this:

try {
   my2DArray = readMyTextFile();
catch (ReadTextFileException rtfe) { // NOT a real exception!

Something like that, but with real code?

So you can see why you can't do that where you tried to do it originally, right? (please explain why, as best you can, so I know that you're following me) (it's okay if you don't get it, I'll explain, but try first!)

Erm, I don't know where to try and catch (read my text file) so that I can equate the output of the reading to my 2D array.

Erm, I don't know where to try and catch (read my text file) so that I can equate the output of the reading to my 2D array.

It seems like you're treating the "try" and "catch" as if they're the importan bits of the operation. They're not. A "try" block is simply a way of marking a block of code for handling. It says "if any exceptions arise within this block, see if you can deal with them using the following catch block(s)". This is required for some operations, like opening and reading from a file.

So what you're stuck on is where you can perform the file read, and wherever you do that, you'll have a try block around it (and an accompanying catch block). Looking at it that way might help you see it more clearly.

The answer, of course, is a matter of design. There are better and worse design choices, but they are choices: there are a number of things that can work, you have to pick one that does.

I will often put the file IO into separate methods, so that my main program is concerned with the higher-level logic. There are two benefits to this. First of all, it segregates the long and uninteresting flie IO code and keeps it out of my way when I'm trying to think about what my program is doing, so I only have to think about the relevant things (ie, the objects in my program). Also very important, it means that the code only appears once in the program. Since the code is, again, long and uninteresting, and also quite fussy in its details, it's something you want to do once and get it done.

All that being said, here's a sketch of a way I'd do it, which you can fill in and use if you like.

public class Foo
//field declarations are up here, including:
int[][] matrix;  // the array I'm going to fill

public static void main(String[] args)
  foo Foo = new foo();  // instantiate an object of this, so we're not static   
  foo.go();             // a trick to get a single-class program running and calling
                        // non-static methods

public void go()
  String fn;             // a filename
  fn = getAFileName();   // either do the input here or sub it out or hard-code the
                         // filename
  matrix = readMatrixFromFile(fn); // ah, that was easy!
  // do stuff with the data, probably using more methods
  // possibly write the output back to fn or into another file


public void getAFileName()
  // this can be as simple as a Scanner on the command line, or you can use Swing 
  // to make a GUI, you don't have to care about how you're getting the filename when
  // you're at the top-level logic.

public int[][] readMatrixFromFile(String fn)
  int [][] newMatrix;
  File file;

  // etc. -  here you would do everything dealing with the file: declare the File 
  // object and related InputStreams and suchlike, open the file, get lines from the 
  // file, and split the lines into elements of your matrix based on your file   
  // format. (assuming that you have rows in separate lines of the input file)
  // The try blocks would necessarily go around the code that throws the exceptions 
  // need to be caught, and the catch blocks would handle the exceptions

  return newMatrix;  

I haven't put in any of the actual code, that's your job. But you can see how the structure makes it easy for me to segregate bits of logic and think about them one at a time - this is why we like modular design. In fact, you could argue that I should separate out the file io even from readMatrixFromFile(). In that design, I'd have a method called, perhaps, "readLinesFromFile(String fn)" - this would open the named file (or gracefully handle an exception) and return the lines contained in it - either one at a time, or preferably, as an array of String. Why is this better?
Well, what if you want to read another file somewhere else, but it doesn't have a matrix in it? This way, you can always get the contents of a file. For example, you might decide that you want to process a bunch of matrices overnight, while you get some sleep. This way, you could put the names of the data files in (you guessed it) a file, and do some batch processing. You'd read the names of the files into an array, and loop over the array, using each lines as an input to "readMatrixFromFile()"
Of course, readMatrixFromFile() then becomes very simple. All it would do would be to go through an array of String and convert each line into an array of ints, and write the output to and int[][] array. That conversion, done with Integer.parseInt(), throws a NumberFormatException, so you might want to use a try block there as well. Where does it get the array of String? Ah, it calls "readLinesFromFile(fn)", passing the filename string along to the method that actually needs it. Cute, no?

Sorry this is so long. I hope you can get some use from it.

Member Avatar

Erm, I don't know where to try and catch (read my text file) so that I can equate the output of the reading to my 2D array.

The simple answer to your question is to look at where the exception might occur. Will you get an exception assigning values to an array, or reading in input?

Most likely, your errors will come from the reading in the text files. Thus, put your try-catch around the areas where you actually read in input. You don't need try-catches around the area where you actually assign values to the 2D array.

import java.io.*;
import java.awt.*;
import javax.swing.*;

public class File
	static double RMSDscores="";
	public static void main(String[] args)
       	    BufferedReader file = new BufferedReader(new FileReader("D:\\project1\\Dynamic Programming\\Alignment Algorithms\\Sequence Testing\\RMSDscores.txt"));	//reading files in specified directory
      		double rmsd;
			while ((rmsd = file.readLine()) != null)	//file reading
  				RMSDscores = rmsd;
		}catch( IOException ioException ) {}    

Okay I have some problem when reading my file. As the info in the text file are all numbers, I want to use double instead of string. However, it cannot be done. May I know how to solve this problem (instead of using string)?

Have a look at the class Double. There's a static method called "parseDouble" that should get you what you need. It takes a String and returns a Double (or perhaps a primitive, a double, one or the other). So you'll break up your input lines into Strings representing each number, and then use this to convert them to Doubles.

Be aware: This will throw a NumberFormatException if it gets a non-numeric value, so the cautious thing to do there is to put the Double.parseDouble() in a try block and handle that exception. That's the cautious thing, but many people skip it, thinking they know what's coming in, so why bother.
Your call.

Hi, I just wanna check if reading how to read a file of numbers? Cause normally when in try and catch statements, while reading, the instance used to read the file is by string. Is there anyway I can read the file using double (since I need to read all the numbers in the file)?