-2

I'm trying to convert a 2d array Queries into array of Objects of type Query. For this purpose, I created a class Query.

class Query{
    int ind, L, R, LB;
}

I'm creating Query array in the following way:

public void solveQueries(int nums, int[][] Queries)
{
    int m = Queries.length;
    Query[] q = new Query[m];
    int sz = (int)Math.sqrt(nums.length);
    
    for(int i=0; i<m; i++){
        q[i].ind = i;
        q[i].L = Queries[i][0];
        q[i].R = Queries[i][1];
        q[i].LB = Queries[i][0]/sz;
        System.out.println(q[i].ind + " " + q[i].L +" "+q[i].R+" "+q[i].LB);
    }
}

I'm getting Exception in thread "main" java.lang.NullPointerException in line q[i].ind = i;

I also tried this approach:

class Query{
    public int ind, L, R, LB;
    
    public void setQuery(int ind, int L ,int R, int LB){
        this.L = L;
        this.R = R;
        this.ind = ind;
        this.LB = LB;
    }
};

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = 5;
    int m = 3;
    int sz = (int)Math.sqrt(n);
    int[] arr = new int[n];
    Query[] q = new Query[m];
    
    //taking array input
    for(int i=0; i<n; i++){
        arr[i] = sc.nextInt();
    }
    
    //taking input for Query
    for(int i=0; i<m; i++){
        int L = sc.nextInt();
        int R = sc.nextInt();
        q[i].setQuery(i, L, R, L/sz);
    }
}

But again I'm getting the same error Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:44) in line q[i].setQuery(i, L, R, L/sz);

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Arya
  • 1
  • 1
  • 1
    `Query[] q = new Query[m];` you created the array but you never put anything in it. – Federico klez Culloca Aug 26 '23 at 08:48
  • 1
    When you create an array, Java does not create objects to fill the array. All the elements of the array are `null`. You need to create the objects yourself: `q[i] = new Query();` – Jesper Aug 26 '23 at 08:51

1 Answers1

1

The NullPointerException you are encountering is due to the fact that you have declared an array of Query objects, but you haven't actually initialized the individual elements of the array. In Java, when you create an array of objects, each element of the array is initially null until you explicitly create instances of those objects using the new keyword. You can modify the second for loop as

for (int i = 0; i < m; i++) {
    q[i] = new Query(); // Initialize each Query object
    int L = sc.nextInt();
    int R = sc.nextInt();
    q[i].setQuery(i, L, R, L / sz);
}

In this code, I've added the line q[i] = new Query(); inside the loop where you are initializing your Query objects. This ensures that you create a new instance of the Query class for each element of the q array before calling the setQuery method.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
BruceWayne
  • 23
  • 6