Convert String[] with text to double[]

后端 未结 5 1148
旧巷少年郎
旧巷少年郎 2021-01-29 15:02

I have an Arraylist that I want to convert to a double[] array. I first convert the Arraylist to a String []. I then try to convert the String[] to a double[] but fail in the p

5条回答
  •  半阙折子戏
    2021-01-29 15:52

    You need to split each String in list1 on "," and attempt to parse each String that gets split out:

        ArrayList results = Lists.newArrayList();
        for( String s : list1 ) {
            String[] splitStrings = s.split(",");
            Double[] doublesForCurrentString = new Double[splitStrings.length];
            for(int i=0; i

    Crucial points:

    • EDIT: As @Tim Herold points out, you're probably better of performance-wise avoiding attempting to parse content you know to be non-numeric. In this case, I'd still split first and then just put in code that prevents you from attempting to parseDouble() on the first split String in each line, rather than trying to do String replacement before the split; that will be faster (and if we're not concerned about performance, then try/catch is perfectly fine and more readable). ORIGINAL: You need a try/catch when you try to parse the doubles, in case there's any invalid input. Bonus: you don't need to remove the non-numeric text now, you can just let this try/catch handle it.
    • Your strings have two doubles in each of them. You're not going to be able to just strip the text at the beginning and then parse the rest, because it's not going to be a valid double.
    • ArrayLists are generally easier to use; I'd opt for returning ArrayList (or ArrayList>) over Double[] or Double[][] any day of the week. There are certainly situations where I'd do differently, but yours doesn't sound like one of them to me.

提交回复
热议问题