So I need to convert and array of Strings that I'm pulling from an API to an array of Doubles so I can use them in some calculations. Here's what I was testing with:
public static double[] ConvertStringArrayToDoubleArray(String[] sArr)
{
double[] dArr = new double[sArr.length];
for (int i = 0; i < sArr.length; i++)
{
try
{
dArr[i] = Double.parseDouble(sArr[i]);
}
catch (NumberFormatException e)
{
System.out.println("Could Not Convert Properly at position " +
String.valueOf(i));
}
}
return dArr;
}
public static void main(String[] args) throws Exception
{
String[] dmgs = new String[5];
dmgs[0] = "1.2";
dmgs[1] = "1.3";
dmgs[2] = "";
dmgs[3] = "-";
dmgs[4] = "8";
double[] dDmgs = new double[dmgs.length];
dDmgs = ConvertStringArrayToDoubleArray(dmgs);
for (int i = 0; i < dDmgs.length; i++)
{
System.out.println(dDmgs[i]);
}
}
When I ran it I was given this as the output:
Could Not Convert Properly at position 2
Could Not Convert Properly at position 3
1.2
1.3
0.0
0.0
8.0
Which is what I wanted. But when I run it with this array:
[1.5, 1.5, 2.7, 0.3, 1, 6, 10, 8, 3.5, 3, 8.5, 5, 2, 6, 6, 16, 17, 16, 15, 5, 16, 15, , , , 7, 3, 3, 6, 3, 4.5, 3, 5, 8, 6, 4.5, 3, 2.2, 6, 13, 9, 4, 7, 8, 5, 1.35, 2.7, 9, 8.5, 8, 9, 8.5, 8, 8, 6, 6, 7, 6, 6.5, 5, 3, -, 2, -, 0.2, 0.2, 0.2, 3, 3, -, -]
I get this instead:
[1.5, 1.5, 2.7, 0.3, 1.0, 6.0, 10.0, 8.0, 3.5, 3.0, 8.5, 5.0, 2.0, 6.0, 6.0, 16.0, 17.0, 16.0, 15.0, 5.0, 16.0, 15.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 8.0, 6.0, 4.5, 3.0, 2.2, 6.0, 13.0, 9.0, 4.0, 7.0, 8.0, 5.0, 1.35, 2.7, 9.0, 8.5, 8.0, 9.0, 8.5, 8.0, 8.0, 6.0, 6.0, 7.0, 6.0, 6.5, 5.0, 3.0, 0.0, 2.0, 0.0, 0.2, 0.2, 0.2, 3.0, 3.0, 0.0, 0.0]
*I'm using Arrays.toString() to print these so that's why there are the spaces.
Anyways, for the life of me I can't figure out what is going on the conversion's at positions 22 through 28 since it seems to be working fine and not bugging out in the test I ran. I would assume it would just have only position 22 through 24 set to 0.0 and then continue on at position 25 with 7.0 but its not doing that.
How do I fix this?