Reputation: 55
I keep on getting a null pointer exception and I have no idea why. Explain please.
public static int[][] convertStringToInt(String[][] array){
int [][] numbers = new int [array.length][];
for(int row = 0; row < array.length; row++)
{
numbers[row] = new int [array[row].length]; //line 48
for(int col = 0; col < array[row].length; col++)
{
numbers[row][col] = Integer.parseInt(array[row][col]);
}
}
return numbers;
}
public static void main (String[] agrs)
{
File selectedFile = selectFile("Enter fileName for double number, EX:
decimalNumbers.csv");
if( !selectedFile.exists())
{
System.out.print("\nFile does not exit, program terminating\n\n");
System.exit(1);
}
int countLines = countLinesInFile(selectedFile);
String cities [][] = loadArrayFromFile(selectedFile, countLines);
int [][] unitsSold = convertStringToInt(cities); //line 157
System.out.println(unitsSold);
}
here are the errors when i enter the file name
Exception in thread "main" java.lang.NullPointerException
at labReview.ArrayOfArrays.convertStringToInt(ArrayOfArrays.java:48)
at labReview.ArrayOfArrays.main(ArrayOfArrays.java:157)
Upvotes: 0
Views: 435
Reputation: 497
I guess, you have a null array in your cities at some index.
String cities [][] = loadArrayFromFile(selectedFile, countLines);
Try printing your cities array as below
for(String[] cityArr : cities){
System.out.println("Cities at Index "+i+" is : "+citiArr);
}
And if you see a "null" value at any index, then modify your loadArrayFromFile to replace a black array whenever you have a null while adding it to cities array.
....
if(citiArr==null){
citiArr = new String[]{};
}
cities[i][j]=citiArr;
....
Upvotes: 0
Reputation: 34146
The method convertStringToInt
works fine. The exception you described NullPointerException
may occur in the line
numbers[row] = new int[array[row].length];
if array[row]
is null
. So the error may be occuring because the method loadArrayFromFile
is returning a null
row, like this (for example):
String[][] s = { { "1", "2", "3" }, { "1" }, null, { "3", "4" } };
Print the elements in the array returned by the method loadArrayFromFile
to see if there are null
rows.
Upvotes: 1