0

I have the code bellow which reading a file to Arraylist and convert it to 2D array :

   public double [][] filetoArray(String fileName)
        throws IOException
    {

      ArrayList result = new ArrayList();

      File aFile = new File(fileName);

   BufferedReader reader = new BufferedReader(new FileReader(aFile));


    String aLine = null;

    while ((aLine = reader.readLine()) != null)
    {
         //result.add(aLine + ",");
         result.add(aLine);
        //aLine = reader.readLine();
    }

    String[][] data = new String[result.size()][result.size()];


   for(int i =0; i < result.size()/2; i++){
      for(int j =0; j <2; j++){
       data[i][j]= (String) result.get(j +( result.size() * i));
     }
  }

I have an error ( filetoarray) can not cast string to double ? i have also array out of bound exception when just use the string type with out casting to double?

any suggestion please

novin
  • 55
  • 6

2 Answers2

0

In Java, String is not directly castable to double. What you need is Double.valueOf(someString) or Double.parseDouble(someString).

Edit: Looks like even if you fix this problem, you will end up with IndexOutOfBoundsException.

If your list size is say 4, and at some point i == 1 and j == 1, you will end up with . 1 + (4 * 1) which is 5.

Average Joe
  • 643
  • 5
  • 15
0

The following snippet will convert the arrayList to Double array for even number of lines in the file with data that can be parsed by class Double

public static double[][] filetoArray(String fileName) throws IOException {

    ArrayList<String> result = new ArrayList<String>();

    File aFile = new File(fileName);

    BufferedReader reader = new BufferedReader(new FileReader(aFile));

    String aLine = null;

    while ((aLine = reader.readLine()) != null) {
        result.add(aLine);
    }
    double[][] data = new double[result.size()/ 2][2];

    int init = 0;
    for (int i = 0; i < result.size() / 2; i++) {
        for (int j = 0; j < 2; j++) {
            data[i][j] = Double.parseDouble(result.get(init));
            init++;
        }
    }
    return data;
}
Loki
  • 801
  • 5
  • 13