0

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

3
  • 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 be Commented 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. Commented Sep 13, 2009 at 17:42
  • Thanks folks, Still having trouble but i'll ask in a seperate post to clarify things. Cheers again. Commented Sep 13, 2009 at 18:20

4 Answers 4

4
 String[] doubles = myString.split(",");

then iterate over the doubles array and do Double.parseDouble();

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

Maybe something like:

String[] sa = yourString.split(",");
Double[] da = new Double[sa.length];
int idx = o;
for(String s : sa) {
   da[idx++] = Double.parseDouble(s); 
}

Comments

0

Split the string based on the ',' and store into a string array.

String[] arr= Str.split(",");

Then make a double array and put the each str values into that double array.

Double[] res= new Double[arr.length];
for(int i=0;i<arr.length;i++){
    res[i] = Double.parseDouble(arr[i]); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.