Reputation: 330
The following code is gives a NullPointerException when i input the array elements. After debugging and analyzing i got to find that the exception is encountered only when i am using a 3d array. For 2d it works fine. Obviously for some reason the array is taking null as inputs. Can someone explain this? Maybe something is wrong about the 3d array.
Edit: Also,in my case the value of the 3rd dimension is not known as it would depend on the value of arr[0][0][0] which needs to be input first. So the 3rd dimension length should be assigned at runtime.
import java.util.*;
public class NewClass
{
public static void main(String args[])
{
int T;
Scanner sc = new Scanner (System.in);
T=sc.nextInt();//this works fine
int arr[][][]= new int[T][4][];
for(int i=0;i<T;i++)
{
for(int j=0;j<3;j++)
{
arr[i][j][0]=sc.nextInt();//NullPointerException after input
}
}
}
}
Upvotes: 0
Views: 50
Reputation: 17890
You haven't specified (or initialized) the third dimension.
You can change the arr
initialization as
int arr[][][]= new int[T][4][1];
Or can create the array of the third dimension inside the inner for loop
for(int j = 0; j < 3; j++) {
arr[i][j] = new int[1];
arr[i][j][0] = sc.nextInt();
}
Upvotes: 8