[英]Trouble copying a CSV into an array in java
所以這是我第一次嘗試做這樣的事情,而且我一直在從各種來源在線收集有關如何正確執行此操作的信息。 到目前為止,我已經編寫了一個代碼,相信可以完成該代碼。 但是,每當我單擊運行時,程序都會終止並顯示此錯誤:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Version,1.4.0"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at IO_CSV.setUpMyCSVArray(IO_CSV.java:47)
at IO_CSV.main(IO_CSV.java:82)
這是我的代碼:
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.NumberFormat;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class IO_CSV {
static String xStrPath;
static double[][] myArray;
NumberFormat nf = NumberFormat.getInstance();
static void setUpMyCSVArray()
{
myArray = new double[3000][3000];
Scanner scanIn = null;
int RowC= 0;
int Row = 0;
int ColC = 0;
int Col = 0;
String InputLine = " ";
String xfileLocation;
xfileLocation = "/Users/victorgarcia/Documents/reza_data1.csv";
try
{
//setup scanner
scanIn = new Scanner(new BufferedReader(new FileReader(xfileLocation)));
//while ((InputLine = scanIn.nextLine()) != null)
while(scanIn.hasNextLine())
{
//read line in from file
InputLine = scanIn.nextLine();
//split the InputLine into an array at the commas
String[] InArray = InputLine.split(",,,");
//copy the content of the inArray to the myArray
for(int x = 0; x< InArray.length; x++)
{
myArray[RowC][x] = Double.parseDouble(InArray[x]);
}
//increment the row in the array
RowC++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
static void printMyArray()
{
for (int RowC=0; RowC<3000; RowC++)
{
for (int ColC=0; ColC<3000; ColC++)
{
System.out.print(myArray[RowC][ColC]+ " ");
}
System.out.println();
}
return;
}
public static void main(String[] args)
{
setUpMyCSVArray();
}
}
希望有人對我做錯了什么
在此代碼中,您假定CSV中的所有值都可以解析為double。 字符串“ Version,1.4.0”並非如此,它顯然出現在文件中。 要捕獲此問題並記錄無法將值解析為雙精度值的所有其他情況,可以更改代碼,如下所示:
try
{
myArray[RowC][x] = Double.parseDouble(InArray[x]);
}
catch (NumberFormatException nfe)
{
System.out.println("Unable to parse at " + rowC + ", " + x + ": " + InArray[x]);
}
盡管創建一個簡單的自制CSV解析器相對容易,但實際上它比表面上看起來要復雜得多。 最后,您可能會花費大量的時間來解決類似您在此處遇到的問題,因此通常不值得實現自己的問題。 有很多可用的開源實現(例如Commons CSV )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.