Question

I'm trying to read my file in notepad using CSVReader but I cannot get it work. it says ArrayIndexOutOfBoundsException: 2 line "y[i][2]". eventhough I intiallize my array rows in 100. I'm currently new in using Java and CSVReader.

public static void main(String[] args) throws IOException {

    double[][] x = new double[100][3];
    double[][] y = new double[100][1];

    String line[];
    try{
        CSVReader br=new CSVReader(new FileReader("ex2data2.txt"),',');
        int i = 0;
        while((line=br.readNext())!=null){
            x[i][0] = Double.parseDouble(line[0]);
            x[i][1] = Double.parseDouble(line[1]);
            y[i][2] = Double.parseDouble(line[2]);
            i++;
        }
        br.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
Was it helpful?

Solution

It's completely unclear as to why you would be storing the data as you are after reading it from the file, but ...

double[][] y = new double[100][1];

This allocates an array of 100 double arrays, each with a length of 1

Here:

 y[i][2] = Double.parseDouble(line[2]);

You attempt to store something at the third element of one of those 100 arrays. They aren't that large; you created them to have a length of one.

I suspect you meant to do:

 y[i][0] = Double.parseDouble(line[2]);

since the only thing you're storing in the y arrays is that single value.

All that being said, this is a poor way to store these values. In general you are better served using a dynamic data structure so you don't have to worry about what the length (number of lines) of the file is. In addition, why would you need two different 2D arrays? Even a List<Double[]>, for example, would be better.

OTHER TIPS

You have create

double[][] y = new double[100][1];

i.e. 100 rows and 1 column. but trying to put value at position y[i][2]. thats why you are getting ArrayIndexOutOfBoundsException. create like

double[][] y = new double[100][3];

or you can simply put value as (in this case you don't need to create 2D array given as above)

y[i][0] = Double.parseDouble(line[2]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top