簡體   English   中英

將字符串數組拆分為雙精度數組並計算java中所有值的平均值

[英]Splitting a string array into a double array and calculating the average of all the values in java

我正在嘗試拆分一個字符串數組 (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) 然后將值分配給一個雙數組,然后計算所有值的平均值。 我的代碼:

    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
    }

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

您用於String#split()方法的正則表達式應該是這樣的:

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

現在您需要做的就是將數組中的 double 類型值相加(在for循環中)並除以dblArray.length以獲得平均值(在for循環之后)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM