[英]Writing a array to import csv to java
我嘗試編寫一個Java程序來導入一個csv文件,並將數據放入數組中,並且需要將字符串轉換為日期並加倍。 最后,我想將結果打印到屏幕上,以顯示我的程序是否運行良好。
它實際上是我的大學之一。 用戶需要輸入日期作為參數的作業。
在我寫完所有代碼並嘗試運行它之后,它顯示以下錯誤消息:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.