gpt4 book ai didi

java - 编写数组将csv导入java

转载 作者:行者123 更新时间:2023-11-30 03:41:04 25 4
gpt4 key购买 nike

我尝试编写一个java程序来导入csv文件并将数据放入数组中,并且需要将字符串转换为日期和 double 。最后我想将结果打印到屏幕上以显示我的程序是否运行良好。

这实际上是我的大学之一。用户需要输入日期作为参数的作业。

在我编写完所有代码并尝试运行它之后,它显示了以下错误消息:

Exception in thread "main"java.lang.ArrayIndexOutofBoundsException: 0 
at ReadCSV.main(ReadCSV.java:10)

有人可以告诉我我在程序中犯了什么错误吗?

  import java.util.*;
import java.text.*;'
import java.io.*;
import java.text.ParseException;

public class ReadCSV {
public static void main(String[] args) throws IOException, ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate, endDate;
startDate = sdf.parse(args[0]);
endDate = sdf.parse(args[1]);
File file = new File("table.csv");
Scanner inputfile = new Scanner(file);
inputfile.next();
inputfile.next();
int count ;
count = NumRows();
Date[] date_tr = new Date [count];
Double[] open = new Double[count];
Double[] high = new Double[count];
Double[] low = new Double[count];
Double[] close = new Double[count];
int i = 0;

while(inputfile.hasNext()){
String data_row = inputfile.next();
String[] data = data_row.split(",");
date_tr[i]=sdf.parse(data[0]);
open[i]=Double.parseDouble(data[1]);
high[i]=Double.parseDouble(data[2]);
low[i]=Double.parseDouble(data[3]);
close[i]=Double.parseDouble(data[4]);
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println( outFormat.format(date_tr[i]) + " " + open[i] + " " + high[i] + " "+ low[i]+ " " + close[i]);
i++;
}
inputfile.close();
}
public static int NumRows() throws IOException{
File file = new File("table.csv");
Scanner inputfile = new Scanner(file);
inputfile.next();
inputfile.next();
int count = 0;
while (inputfile.hasNext()){
String data_row = inputfile.next();
count++;
}

return count;
}

}

最佳答案

您将需要传递命令行参数。由于您没有传递命令行参数,因此您的代码在此处失败:

startDate = sdf.parse(args[0]);
endDate = sdf.parse(args[1]);

它试图在索引 0 和 1 处查找您未传递的参数。

您需要运行如下命令:

java ReadCSV 2014-09-28 2014-10-28

关于java - 编写数组将csv导入java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26807282/

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