I have a string that will be different each time but follow the form of -3.33,-46.53,37.39,26.55,97.11,68.46,-32.46,-5.89,-62.89,-7.9, and i want to remove each number and store as an double in an array. even pseudocode would be great i'm drawing a blank. Cheers
-
Cheers folks, Just wondering would I be better off using an arraylist as I'm reading from a file and don't know how big each file will beNick– Nick2009-09-13 16:36:08 +00:00Commented Sep 13, 2009 at 16:36
-
You should try asking that as a separate question with some more details, but if you have an unknown amount of lines like these, then that is what an Array list was designed for. If it is all on one line, read in memory at once, then a pre-allocated array makes some sense.Yishai– Yishai2009-09-13 17:42:46 +00:00Commented Sep 13, 2009 at 17:42
-
Thanks folks, Still having trouble but i'll ask in a seperate post to clarify things. Cheers again.Nick– Nick2009-09-13 18:20:00 +00:00Commented Sep 13, 2009 at 18:20
Add a comment
|
4 Answers
Alternative way, reads input from file and parses items as thy are read.
static java.util.ArrayList<Double> getData(String filename) throws FileNotFoundException {
java.util.ArrayList<Double> result = new java.util.ArrayList<Double>();
java.util.Scanner sc = new java.util.Scanner(new java.io.File(filename));
sc.useDelimiter(",");
while (sc.hasNext())
result.add(Double.parseDouble(sc.next()));
sc.close();
return result;
}
If you want, you can just store them in a array like:
Double data[] = null;
getData("input.dat").toArray(data);