0

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```
1
  • Unrelated to your issue, but the entire getRow() method can be replaced with a call to Arrays#copyOf(). Commented Feb 26, 2021 at 22:04

1 Answer 1

3

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];
Sign up to request clarification or add additional context in comments.

1 Comment

A good reminder to be diligent with bugfixing! Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.