简体   繁体   中英

Array is empty once filled? (Java)

I am relatively new to Java. I am trying to read a .csv file and make some calculations on it. I succesfully managed to read the file and get the data in the form of a String structured as the csv, with " " (spaces) instead of commas, then I'd like to turn the number (strings) into doubles and stock them in the array.

The dataArray is declared in the class as follows:

public double dataArray[][];

For some reason i get an empty array (an array full only of 0.0) after having run the following method to fill it:

//Store value into the array
public void toArray()
{
    try
    {
        int nrows = this.text.split("\n").length;
        int ncolumns =this.text.split("\n")[0].split(" ").length;
        //System.out.println(nrows);
        //System.out.println(ncolumns);
        this.dataArray = new double[nrows][ncolumns];
        for(int i=0; i<nrows ;i++)
        {
            for(int k=1; k<(ncolumns-1);k++)
            {
                double number = Double.parseDouble(this.text.split("\n")[i].split(" ")[k]);  //Double.parseDouble(this.text.split("\n")[i].split(" ")[k]);
                this.dataArray[i][k] = number;
            }
        }
    }catch(Exception e)
    {
        System.out.println(e);
    }
}

What am I doing wrong? I tried several fix, even using other methods in this method but haven't find a solution yet..

EDIT: Fixed k which was wrong

Instead of debugging your code, I propose you a working snippet that does what you need :

public void toArray() {
    String[] split = this.text.split("\n");
    this.data = new double[split.length][];
    for (int i=0 ; i<data.length ; i++) {
        String[] cols = split[i].split("\\s+");
        data[i] = new double[cols.length];
        for (int j=0 ; j<cols.length ; j++)
            data[i][j] = Double.parseDouble(cols[j]);
    }
}

Tested on : text = "1 2 3 4\\n5 6 7 8\\n9 10 11"

Output : data = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM