Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV input to two dimmensional array in java

Tags:

java

arrays

csv

I have a read() method and inside I want to separate the Strings(which have spaces between them) and putting them in a two dimensional array, but before that I get rid of all the spaces. After the array initialized, it is given to the CSV constructor and that is creating its own 2D array. The problem is that I always get the following error: "variable sr might not have been initialized" at CSV csv = new CSV(sr). How do I make sure that my array gets the valid String?

private String[][] tomb;

private CSV(String[][] t2) {
    tomb = new String[t2.length][];
    for(int i = 0; i < t2.length; i++) {
        tomb[i] = new String[t2[i].length];
        for(int j = 0; j < t2[i].length; j++) {
            tomb[i][j] = t2[i][j];
        }
    }
}

public static CSV read(Scanner sc) {

    String[][] sr;    
    int n = 0;
    while (sc.hasNextLine()) 
    {
        String line = sc.nextLine();
        String[] str = line.split(",");
        sr = new String[str.length][];
        for (int i = 0; i < str.length; i++) {
            sr[i][n].replaceAll("\\s+","");

        }
        n++;
    }

    CSV csv = new CSV(sr);
    return csv;

}
like image 783
Akos Fajszi Avatar asked Jan 22 '26 17:01

Akos Fajszi


1 Answers

You can resolve the error by setting sr to null in the initialization:

String[][] sr = null;

If you want to make sure sr was set correctly, you can check if sr is still null after the while loop completes.

like image 77
Libby Avatar answered Jan 24 '26 05:01

Libby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!