你好,这是我第一次发帖,如果我在提问过程中做错了什么,请告诉我。
我的目的:将双变量保存在 csv 文件中,并将它们保存在 java 文件中的数组列表中。
到目前为止我有当前的代码,我是 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)
非常感谢你的帮助。