【发布时间】:2020-12-11 04:35:19
【问题描述】:
第一次提问....
好的,所以我有一个 .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
【问题讨论】:
-
这个 for 循环
for (int i = 1; i < items.length; i++)的逻辑是错误的,因为您在该行的每个项目上调用processData,而是应该为每一行调用一次processData -
是的,这是正确的,但我不知道如何逐行分隔。