newbie
newbie

Reputation: 161

How can I return an array out of try-catch block in java?

I created a 2D array from reading a file and I want to return this array. However I use try-catch block because of reading file. At this point I can't return this array from this function.Also when I try to write the elements of this array in try-catch block, it works but out of block it doesn't. What should I do to get the array?

My code is as below:

 public static double[][] readFile(String fileName)  {
     final double[][]data = new double[178][13];
      int x=0, y=0;
    try{
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line;
    while((line = reader.readLine())!= null){
        String[]values=line.split(",");
        for(String str:values){
            double str_double=Double.parseDouble(str);
            data[x][y]=str_double;
            System.out.print(data[x][y]+" ");
        }
        System.out.println();
    }
    reader.close();

    }
    catch(Exception e){}

     return data;

 }

Finally, with helps of everyone I found a solution. One of my mistake is defining y. Beacuse each line has 14 elements but I assigned it to 13. Also I changed assignment method of array. Maybe anyone needs, so I post it to here my solution:

public static double[][] readFile(String fileName)  {
      double[][]data=new double[178][14];
      int x=0, y;
    try{
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line;
    String[]values;
    while((line = reader.readLine())!= null){


        values=line.split(",");

       for(y=0; y<values.length; y++){
           data[x][y]=Double.parseDouble(values[y]);
       }
       x++;
    }



    reader.close();

    }
    catch(Exception e){System.out.println("Aborting due to error: " + e);}

     return data;

 }

Upvotes: 1

Views: 3515

Answers (2)

PNS
PNS

Reputation: 19905

The original code assigns only one value at the array, i.e. the element data[0][0], since x and y never change from 0.

Assuming that x is the line and y is the column (element in the line), the following should work:

public static double[][] readFile(String fileName) {
     final double[][]data = new double[178][13];
      int x, y;
    try{
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line;
    x = 0; // Reset the line counter
    while((line = reader.readLine()) != null) { // Read a new line
        y=0; // Reset the column counter, since this is a new line 
        String[]values=line.split(",");
        for(String str:values){
            double str_double=Double.parseDouble(str);
            data[x][y]=str_double;
            System.out.print(data[x][y]+" ");
            ++y; // Advance to the next column
        }
        ++x; // Advance to the next line
        System.out.println();
    }
    reader.close();

    } catch (Exception e) {
        System.out.println("Aborting due to error: " + e);
    }    
     return data;    
 }

The above assumes, of course, that no errors occur as a result of calling readLine() or parseDouble(). If any such error happens, or an ArrayIndexOutOfBoundsException occurs, the returned array will only contain the elements read thus far.

Here is an improved version, again maintaining as much of the original code as possible:

public static double[][] readFile(String fileName) {
    ArrayList<double[]> numbers = new ArrayList<double[]>();        

    try {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line;

        while ((line = reader.readLine()) != null) { // Read a new line             
            int y=0; // Reset the column counter, since this is a new line 

            String[] values = line.split(",");

            if (values.length > 0) {
                double[] elements = new double[values.length];

                for (String str:values) {
                    double str_double;
                    try {
                        str_double = Double.parseDouble(str);
                        elements[y] = str_double;
                        System.out.print(elements[y] + " ");
                        ++y; // Advance to the next column
                    } catch (Exception e) {
                        continue; // Not a double, ignore
                    }
                }                   
                numbers.add(elements);                  
            } else {
                numbers.add(new double[0]); // No numbers read from the line
            }
            System.out.println();
        }                       
        reader.close();
    } catch (Exception e) {
        System.out.println("Aborting due to error: " + e);
    }

    return numbers.toArray(new double[0][0]);
}

Neither of the two versions is tested, but they should both be close to a working solution.

The second approach is more generic and should be preferred, although, to avoid boxing/unboxing between double and Double, it assumes that, if any element read as a string is not a valid double, the corresponding position in the elements array will be filled by the next valid double, if any. So, if, for example, there are 10 elements in a line and only 8 of them are valid in total, then the first 8 positions of the array will contain the values of these elements and the last 2 positions will contain 0 (set during the initialization of the elements array).

Upvotes: 1

Acewin
Acewin

Reputation: 1727

There is no specific need for declaring the variable as a final variable. You need not declare it as private as well.

simple

double[][]data = new double[178][13];

variable declaration is incorrect

Upvotes: 0

Related Questions