'Splitting a string array into a double array and calculating the average of all the values in java
I am trying to split a String array (1.29\r1.31\r1.30\r1.29\r1.30\r1.30\r1.31\r1.27\r1.28\r1.27\r1.25\r1.29\r) and then assign the values to a double array which would then compute the average of all the values. My code:
public void process(String data) {
int length = 0;
double total = 0;
String[] split = data.split("\r");
// create double array while ignoring the first element
double[] numbers = new double[split.length-1];
for (int i = 0; i < numbers .length; i++) {
numbers[i] = Double.parseDouble(split[i+1]);
total = total + numbers[i]; //Adds the array value to the total
length = length + 1;
}
averageRate = total / length; //Equation used to compute the average
}
The output:
1.29\r1.31\r1.30\r1.29\r1.30\r1.30\r1.31\r1.27\r1.28\r1.27\r1.25\r1.29\r
Average computed: NaN
Now let's do some conversion...
£100.0 gets us on average $NaN
$100.0 gets us on average £NaN
Solution 1:[1]
The Regular Expression you're using for your String#split() method should be fine the way it is:
String data = "1.29\r1.31\r1.30\r1.29\r1.30\r1.30\r1.31\r1.27\r1.28\r1.27\r1.25\r1.29\r";
String[] splitData = data.split("\r");
double[] dblArray = new double[splitData.length];
for (int i = 0; i < splitData.length; i++) {
dblArray[i] = Double.parseDouble(splitData[i]);
}
System.out.println(Arrays.toString(dblArray));
Now all you need to do is sum up the the double type values in the array (while in the for loop) and divide by dblArray.length to get the average (after the for loop).
Solution 2:[2]
String input = "1.29\r1.31\r1.30\r1.29\r1.30\r1.30\r1.31\r1.27\r1.28\r1.27\r1.25\r1.29\r";
double avg = Arrays.stream(input.split("\r"))
.collect(Collectors.averagingDouble(a -> Double.parseDouble(a)));
System.out.println(avg);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DevilsHnd |
| Solution 2 | Ryan |
