简体   繁体   中英

The 3d array is taking null as inputs using Java.util.Scanner.nextInt()

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

            }

        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM