您好,這是我第一次發佈,請讓我知道如果我在問題詢問過程中做錯了什麼。如何將csv文件中的數字保存到java arraylist中
我的目的是:在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)
非常感謝你的幫助。
見http://stackoverflow.com/a/105649/647772 – 2012-10-28 14:15:34