gpt4 book ai didi

java - 在 java 中将 CSV 复制到数组时遇到问题

转载 作者:行者123 更新时间:2023-12-01 12:20:41 25 4
gpt4 key购买 nike

所以这是我第一次尝试做这样的事情,我一直在网上从各种来源收集有关如何正确执行此操作的信息。到目前为止,我已经编写了一段代码,我相信它能够完成工作。但是,每当我单击“运行”时,程序都会终止并打印此错误:

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”的情况并非如此,它显然出现在您的文件中。要捕获此问题并记录该值无法解析为 double 的所有其他情况,您可以像这样更改代码:

try
{
myArray[RowC][x] = Double.parseDouble(InArray[x]);
}
catch (NumberFormatException nfe)
{
System.out.println("Unable to parse at " + rowC + ", " + x + ": " + InArray[x]);
}

关于java - 在 java 中将 CSV 复制到数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com