Akos Fajszi Akos Fajszi - 1 year ago 72
Java Question

CSV input to two dimmensional array in java

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++) {


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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download