2014-10-31 50 views
0

因此,这是我第一次尝试这样做,并且我一直在线收集各种来源的信息,以了解如何正确执行此操作。到目前为止,我已经写了一个我相信能够完成工作的代码。但是,每当我点击运行,程序将终止并打印此错误:将java复制到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(); 


} 
} 

希望有人对我一个答案,我在做什么错

+1

你能给我们一个样本输入文件吗?你错误地解析它,所以有个例子可以指导你 – Dici 2014-10-31 20:02:55

+0

另外要注意:你的printMyArray()方法可以改进。而不是硬编码的值你可以简单地做:静态无效printArray(double [] [] toPrint){for(int x = 0; x user2494817 2014-10-31 20:07:02

回答

1

在此代码中,您假定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]); 
} 
0

虽然这是比较容易想出了一个简单的自制CSV解析器,它实际上比从表面看来更复杂的问题。最后,你最终可能花费相当多的时间来抛出你在这里遇到的问题,所以实施你自己的问题通常是不值得的。有很多开源实现可用(如Commons CSV)。