Reputation: 13
I have been attempting to find the null pointer issue for days. The code compiles fine but when it is run the message java.lang.NullPointerException at RandomArray.getRow(RandomArray.java:28) [this being the line indicated below <--]
Am I stupid?
//An instance variable to hold an array of integers
int[][] intHolder;
public RandomArray(int rows, int cols, int range) {
//Create a 2D array with values between 0-range
int[][] intHolder = new int[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
intHolder[i][j] = (int)((range-1)*Math.random());
System.out.println(intHolder[i][j]); //PRINT FOR TESTING
}
}
}//constructor
public int[] getRow(int r){
//Return a copy (clone) of row r of the array
int[] arrayReturn = new int[intHolder[r].length]; //I was having problems here too, no idea why this works
for(int i = 0; i < intHolder[r].length; i++){
arrayReturn[i] = intHolder[r][i]; //The problem is here <--------------
System.out.println(arrayReturn[i]);
}
return arrayReturn;
}//getRow method
public int[] getCol(int c){
//Return a copy (clone) of column c of the array
int[] arrayReturn = new int[intHolder[c].length];
for(int i = 0; i < intHolder[c].length; i++){
arrayReturn[i] = intHolder[c][i];
System.out.println(arrayReturn[i]);
}
return arrayReturn;
}//getCol method
}//RandomArray class```
Upvotes: 0
Views: 58
Reputation: 324128
You have two variables with the same name:
int[][] intHolder;
You define an "instance" variable, but it is null.
public RandomArray(int rows, int cols, int range) {
int[][] intHolder = new int[rows][cols];
The above code defines a "local" variable in the constructor and can't be accessed by any other method.
To initialize your "instance" variable so it can be used in any method you use:
//int[][] intHolder = new int[rows][cols];
intHolder = new int[rows][cols];
Upvotes: 3