Problem reading correctly from a file
Hey guys, so I'm trying to read from a .txt file (which is written in a specific way) and then save some integers in a 2-dimensional array. The .txt file is written like this:
5
4 5 3 2 1
1 3 2 4 5
2 5 3 4 1
1 4 3 2 5
4 3 2 1 5
My code is this:
Code Java:
int[][] protimiseisA = null;
in = new BufferedReader(new FileReader("prefsA.txt"));
//reading the first number
String str = in.readLine();
//saving it for use later
int sum = Integer.parseInt(str);
//reading the empty line and discarding it
str = in.readLine();
//gist of the code, read the next five lines and save the integers in the array
for (int x = 0; x < sum; x++) {
str = in.readLine();
String[] str2 = str.split("\\s+");
for (int y = 0; y < sum; y++) {
protimiseisA[x][y] = Integer.parseInt(str2[y]);
}
}
Of course that's only part of the code but that's where the problem is imo, since it throws a NullPointerException at the line "protimiseisA[x][y] = Integer.parseInt(str2[y]);"
Any help would be greatly appreciated!
Re: Problem reading correctly from a file
So where did you initialize protimiseisA ?
Re: Problem reading correctly from a file
Hm, nowhere. I thought I did initialize it with this line: "int[][] protimiseisA = null;" Should I fill the array with zeros first? Sorry, I'm kinda new to programming...
Re: Problem reading correctly from a file
"int[][] protimiseisA = null;" say the variable protimiseisA is an int[][] type. But assigning anything to null means no memory location has been assigned to the variable, Thus making java throw the nullPointerException. To initialize an array of arrays you will want to use "new insertTypeHere[insertSizeHere][]", if you know the second dimension, put it in, otherwise i think you may need to initialize the inner array. I say I think because its been a while, and I currently don't have a jdk installed on this computer.
Re: Problem reading correctly from a file
Wow, thx so much, I can't believe I missed that... Now time to work on the rest of the code