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);