您好,这是我第一次发帖,如果我在提问过程中做错了,请告诉我。
我的目的:将双变量保存在csv文件中并将它们保存在java文件的arraylist中。
我到目前为止已经有了当前的代码,我是java的初学者,所以请不要点燃ToT
import java.io.*;
import java.util.*;
import java.lang.*;
public class CsvProcessor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// ask for file path at command prompt, save the path input in path
System.out.print("path of file: ");
String path = keyboard.next();
try {
// set up file, reader, and arraylist for processing csv file
java.io.File csv = new java.io.File(path);
BufferedReader bufferedReader = new BufferedReader(new FileReader(csv));
ArrayList<String> csvEntry = new ArrayList<String>();
// set parameters for StringTokenizer
String line = "";
String delimiter = ",";
//read using bufferedReader and save using csvEntry ArrayList
while ((line = bufferedReader.readLine()) != null) {
StringTokenizer stringTokenizer = new StringTokenizer(line, delimiter);
while (stringTokenizer.hasMoreTokens()) {
csvEntry.add(stringTokenizer.nextToken());
}
}
csvEntry.toArray();
double[] csvDouble = new double[csvEntry.getLength()];
for (int i = 0; i < csvEntry.getLength(); i++) {
csvDouble[i] = Double.parseDouble(csvEntry[i]);
}
int x = csvDouble.getLength();
double sum = 0;
for (int y = 0; y < x; y++) {
sum = sum + csvDouble[y];
}
double mean = sum / x;
System.out.println("mean is: " + mean);
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我尝试过转换csv文件中的字符串并将它们保存到arraylist中,然后将arraylist转换为数组,然后将其转换为double数组。 我得到的错误是:
C:\Users\user\Codes\ktrt>java CsvProcessor
path of file: C:\Users\user\Codes\ktrt\montyreal.csv
Exception in thread "main" java.lang.NumberFormatException: For input string: "5
48.53"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.<init>(Unknown Source)
at CsvProcessor.main(csvprocessor.java:27)
非常感谢你的帮助。
答案 0 :(得分:0)
首先,您的错误日志错误。您的代码没有Integer.parseInt()
方法。假设您正确地将CSV解析为csvEntry
变量,这就是您可以做的:
List<Double> csvDouble = new ArrayList<Double>();
double mean, total = 0;
for (String raw : csvEntry) {
double entry = Double.valueOf(raw);
total += entry;
csvDouble.add(entry);
}
mean = total / csvDouble.size();
// at this point you have your ArrayList and mean value;
System.out.println("mean is " + mean);
希望这会有所帮助:)