Hi all, I want to parse the elements in my arraylist to double. May I know how to implement that?

import java.io.*;
import java.util.*;

public class Array2
{

	static ArrayList myDouble = new ArrayList();
	static String[] temp;
	static String[][] finalTemp;
	static String[] arr;
	static int rows;	

	public static void main(String args[])
	{

		try
        {
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

            String str = null;
            while ((str = in.readLine()) != null)	//file reading
            {
				str = str.trim();
				temp = str.split(",");
				myDouble.add(temp);			
            }

            	rows = myDouble.size();
				finalTemp = new String[rows][];

				for (int i=0; i<rows; i++)
				{
  					arr = (String[])myDouble.get(i);
  					finalTemp[i] = arr;
				}

            	for(int i=0; i<rows; i++)
            	{
            		for(int j=0; j<finalTemp[i].length; j++)
            		{
            			System.out.print(finalTemp[i][j]);
            		}
            		System.out.println("");
            	}

			in.close();

        }catch( IOException ioException ) {}

	}

}

This is the codes I have so far. It can print out the output I want. However, I realised I need the 2D array finalTemp to be double, and not string. May I know how can I change it?

Using ArrayList as a raw type isn't a good idea. You can use Java generics to enforce type checking. In other words you can change it to ArrayList<Double> list = new ArrayList<Double>(); in order to allow only Doubles in the list.


That being said, you can use the Double class's parseDouble method to parse a Double from a String. For example, Double result = Double.parseDouble(myString); . You'll need to be careful because an Exception will be generated if the 'myString' variable cannot be converted to a Double, so you will need to use a try/catch and deal with the condition where it can't be parsed appropriately.

The code you posted before would allow you to insert any type of Object into your ArrayList. However, as I've indicated, it is a better idea to keep the list of one type (Double in this case). Then you can use an add() method which takes a String parameter to add Doubles to your list. For example:

String myString = reader.getValueFromUser();

public boolean add(String str)
{
   try {
     //parse the Double in here and add to your list
   } catch(Exception e){
     //do something else here, probably just return 'false'
   }

}

Hope that helps. If any of the above didn't make sense, feel free to ask questions, but you should also check out Java Generics, the Double class documentation, and Exceptions.

Edited 6 Years Ago by BestJewSinceJC: n/a

Hi. When I change my arraylist statement to
ArrayList<Double> list = new ArrayList<Double>(); it doesn't seem to work. I have error saying unexpected type.

The <Double> means you can only put that type into the ArrayList. So if you try to put a String into the ArrayList, then yes, you'll get an error. If that doesn't help, you'll need to post your exact error.

Because I am reading the values from a text file, it is a String, hence how can I not read it as a String? I can't right?

No, you do not have to read it as a String - there are Java library methods that will allow you to read other types from a file. However, that is ignoring the point - that your code, the way you have it now, will work with very minor changes.

Read it in as a String, like you're doing now. Then use the Double.parseDouble() method that I mentioned in my first post to convert the String you just read in into a Double. Then put that Double into your ArrayList<Double> using the ArrayList class's add method.

I guess you are using ArrayList a wrong way...
1)ArrayList is not supposed to hold collection type (array)
2)ArrayList is not suitable to use with multi-dimensional array
3)ArrayList method to get its length is size(). The 'length' is only for primitive array

By the way, I don't know why you need all variables to be static??? Do they still work??? If you are using it just only inside a scope, declare it inside the scope. It is not a good idea to leave local variables as global (as of now for temp, arr, rows, and myDouble).
Not a test code below, but hopefully you would get an idea about how to do it.

import java.io.*;
import java.util.*;

public class Array2 {
  static ArrayList<String> myDouble = new ArrayList<String>();
  static String[] temp;
  static Double[][] finalTemp;
  static String[] arr;

  public static void main(String args[]) {
    try {
      BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

      String str = null;
      int cols=0;
      while ((str = in.readLine()) != null) {
        // file reading
        // expecting each line has exactly the same format
        str = str.trim();
        myDouble.add(str);
        if (cols==0) {  // first time saw a row
          temp = str.split(",");  // do it once to find out the column number
          cols = temp.length;
        }
      }
      in.close();  // you should close the file as soon as you finish reading it!

      finalTemp = new Double[myDouble.size()][cols];  // now can initiate array
      for (int i=0; i<myDouble.size(); i++) {  // myDouble.size() == finalTemp.length
        str = myDouble.get(i);
        // parse it here
        arr = str.split(",");
        for (int j=0; j<arr.length; j++) {     // arr.length == finalTemp[i].length
          finalTemp[i][j] = Double.parseDouble(arr[j]);
        }
      }
    }catch( IOException ioException ) {}
  }
}

Edited 6 Years Ago by Taywin: n/a

I changed it to size() after you copied my code, I guess... The reason is that ArrayList doesn't have 'length' but size() method instead. I already mentioned that in my previous post as well.

Edited 6 Years Ago by Taywin: n/a

I guess you are using ArrayList a wrong way...
1)ArrayList is not supposed to hold collection type (array)

Not a test code below, but hopefully you would get an idea about how to do it.

public static void main(String args[]) {
    try {
 for (int j=0; j<arr.length; j++) {     // arr.length == finalTemp[i].length
          finalTemp[i][j] = Double.parseDouble(arr[j]);
        }
      }
    }catch( IOException ioException ) {}
  }
}

Why isn't it "supposed to be used to hold an array"? An array is an Object and therefore you can use an ArrayList to hold an array. Is it the best idea, usually not, but I'm not sure where you're getting information about that. Also, I thought I should mention that an IOException will not help you if parsing the double fails, since it will throw an InputMismatchException which is *not* an IOException. You either need another catch block (to catch the InputMismatchException) or you need to make your Exception more generic (e.g., Exception)

Yes, you can add a second catch block right after the first one. The second catch block should catch InputMismatchException

This question has already been answered. Start a new discussion instead.