我想修改具有大数据集的 csv 文件的列值。所以我提取了单列值(此处为第二个),然后通过 while 循环的两次迭代查找标准差。第一个用于查找平均值,第二个用于查找标准差。标准偏差乘以提取的值,并用它替换该值。然后生成更新的 csv 文件。在这里,当我运行代码时,它通过没有 while 循环迭代的情况成功生成带有空白文件的新文件。我认为 while 循环有问题或者它没有读取文件。我不知道那是什么?标准差(σ = √[(Σ(x - MEAN))2 ÷ n]) 请帮助我
package csvtest7;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
import java.io.*;
public class Csvtest7 {
public static void main(String[] args)throws IOException {
String filename = "ly.csv";
File file = new File(filename);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("ly_updated.csv"));
}
catch (IOException e) {
}
try {
Scanner inputStream = new Scanner(file);
inputStream.next();
double Tuple;
int count=0;
Tuple = 0;
double stddev=0;
double stddev1;
double stddev2;
//double Xi;
double MEAN;
double standarddeviation;
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(";");
double balance = Double.parseDouble(values[2]);
balance = balance + 1;
Tuple += balance ;
}
MEAN=Tuple/count;
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(";");
double balance = Double.parseDouble(values[2]);
stddev=balance-MEAN;
stddev1=(stddev*stddev);
stddev2=(stddev1/count);
standarddeviation=Math.sqrt(stddev2);
balance=standarddeviation*balance;
values[2] = String.valueOf(balance);
// iterate through the values and build a string out of them
StringBuilder sb = new StringBuilder();
// String newData = sb.toString();
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i < values.length - 1) {
sb.append(";");
}
}
// get the new string
System.out.println(sb.toString());
writer.write(sb.toString()+"\n");
}
writer.close();
inputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Csvtest7.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
您正在跳过第二个 while 循环。
您正在成功执行第一个 while 循环 while (inputStream.hasNext()) {
,直到没有更多 token 可以从文件中读取。现在,您的第二个 while 循环再次显示 while (inputStream.hasNext()) {
现在,由于您已经读取了该文件,因此它不会将指针移回文件开头,并且会表示没有更多 token 可从文件中读取,因此会跳过第二个 while 循环。
解决此问题的一种方法是将 inputStream 重新定义为:
inputStream = new Scanner(file);
while (inputStream.hasNext()) {//start second while loop.
或者
否则在第一个 while 循环中,您可以处理您在第二个 while 循环中尝试执行的操作。您不需要第二个 while 循环。
关于java - 通过提取列值修改并生成新的csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28384978/