首页 > 解决方案 > 一种可以采用 String 格式的整数数组并返回这些数字的平均值的方法

问题描述

第一次问问题。。。。

好的,所以我有一个 .csv 并从中创建了一个字符串数组。我想创建一个从字符串数组中获取数字并返回每行平均值的方法。这是我必须到目前为止的代码。

 while (scan.hasNextLine()) {

        line = scan.nextLine();
        items = line.split(",");

        out += String.format("%10s", items[0]);
        out += "\t";

        for (int i = 1; i < items.length; i++) {

            out += processData(items[i]);
            out += String.format("%.1s",items[1]);
            out += "\t";

        }

        out += " \n";


    }

    scan.close();
    System.out.println(out);

}

public static double processData(String total) {
    String[] val = total.split(" ");
    double[] array = new double[val.length];
    double lineCount = 0;
    double ave = 0;
    double temp =0;

    for (int i = 0; i < val.length; ++i) {
         lineCount++;
         array[i] += Double.parseDouble(val[i]);
         temp += array[i];
         ave = temp/lineCount;
    }
        return ave;

}

这就是输出。

  elephant  651.06  664.06  660.06  664.06  666.06  665.06  655.06  661.06  657.06   
chimpanzee  242.02  245.02  241.02  230.02  237.02  245.02  247.02  232.02  245.02  234.02   
    gerbil  23.02   26.02   22.02   26.02   22.02   22.02   23.02   24.02   23.02   24.02    
   gorilla  257.02  259.02  256.02  257.02  257.02  255.02  259.02  258.02   
   leopard  94.09   95.09   92.09   95.09   95.09   93.09   93.09   93.09   92.09   95.09    
      orca  543.05  547.05  540.05  485.05  552.05  502.05  551.05

这就是理想的输出应该是什么。

elephant   660.3
chimpanzee 239.8
gerbil     23.5
gorilla    257.3
leopard    93.7
orca       531.4

标签: javaarrayscsv

解决方案


我认为您只需要打印平均值和第一列

StringBuilder strBuilder = new StringBuilder();
while (scan.hasNextLine()) {
    line = scan.nextLine();
    items = line.split(",");

    strBuilder.append(items[0]);
    strBuilder.append("\t");
    double sum = 0;
    for (int i = 1; i < items.length; i++) {
       sum += Double.parseDouble(items[i])
    }

    strBuilder.append(sum/(items.length-1));
    strBuilder.append("\n");
}

scan.close();
System.out.println(out.toString());

如果你正在使用java8那么;

private static String processLine(String[] items) {
  StringBuilder strBuilder = new StringBuilder(items[0]);
  strBuilder.append("\t");
  double sum = Arrays.stream(items)
    .skip(1)
    .mapToDouble(Double::parseDouble)
    .sum();
  strBuilder.append(sum/(items.length - 1))
  return strBuilder.toString();
}

String out = Files.readAllLines(pathToCsvFile).stream()
    .map(x -> x.split(","))
    .map(x -> processLine(x))
    .collect(Collectors.joining("\n"));

推荐阅读