Stella chan
Stella chan

Reputation: 11

Writing a array to import csv to java

I try a write a java program to import a csv file and put the data to array, and need to convert the string to date and double. last I want to print out the result to the screen to show whether my program work well or not.

It is actually one of my uni. homework which the user need to input the date as args.

After I wrote all code and tried to run it, it showed the following error message:

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

Can someone tell me what is the mistake that I made in the program??

  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;
  }

}

Upvotes: 1

Views: 91

Answers (1)

SMA
SMA

Reputation: 37083

You will need to pass the command line argument. Since you are not passing command line argument, your code is failing here:

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

It's trying to find argument at index 0 and 1 which you didn't passed.

You would need to run command like:

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

Upvotes: 2

Related Questions