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
I would do this:
then this code
for (String s: list1) {
boolean obtained = false;
double tempD;
try {
tempD = Double.parseDouble(s);
obtained = true;
} catch (Exception e) {
e.printStackTrace();
}
if (obtained) {
list2.add(tempD);
}
}
Loop throug the Array:
foreach String[]
double[counter] = parseToDouble(String[counter])
EDIT:
Java:
String[] str1 = list1.toArray(str1);
double[] dou1 = new double[str1.length]
for(int counter = 0; counter < str1.length;counter++)
dou1[counter] = Double.parseDouble(str1[counter].replaceAll("RSP_\\d+",""));
This will do the work.
double[] doubles = new double[array1.length];
for(int i=0; i<array1.length; i++){
doubles[i] = Double.valueOf(array1[i])
}
Thanks SmartLemon for the edit, you could do this too instead of using a String[]
:
double[] doubles = new double[list1.size()];
for(int i=0; i<list1.size(); i++){
doubles[i] = Double.valueOf(list1.get(i).replace("RSP_\\d+",""));
}
EDIT: So yes, you need a delimiter:
double[] doubles = new double[array1.length*2]; //multiply by 2 because you really have 8 numbers not 4
String [] array2 = null;
for(String string: array1) {
array2 = string.split(",");
for(int i=0; i<array2.length; i++){
doubles[i] = Double.valueOf(array2[i]);
}
}
this should do the work for sure.
Use this
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
double[] doubleArray = new double[str1.length]
int i=0;
for(String s:str1){
doubleArray[i] = Double.valueOf(s.trim());
i++;
}
You need to split each String in list1 on "," and attempt to parse each String that gets split out:
ArrayList<Double[]> results = Lists.newArrayList();
for( String s : list1 ) {
String[] splitStrings = s.split(",");
Double[] doublesForCurrentString = new Double[splitStrings.length];
for(int i=0; i<splitStrings.length; i++){
try {
doublesForCurrentString[i] = Double.valueOf(splitStrings[i]);
} catch( NumberFormatException ex ) {
// No action.
}
}
results.add(doublesForCurrentString);
}
Double[][] doubleArray = (Double[][])results.toArray();
Crucial points:
ArrayList<Double>
(or ArrayList<ArrayList<Double>>
) 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.