简体   繁体   English

3d数组使用Java.util.Scanner.nextInt()将null作为输入

[英]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. 当我输入数组元素时,以下代码给出了NullPointerException。 After debugging and analyzing i got to find that the exception is encountered only when i am using a 3d array. 经过调试和分析后,我发现只有在使用3d数组时才会遇到异常。 For 2d it works fine. 对于2d,效果很好。 Obviously for some reason the array is taking null as inputs. 显然由于某种原因,该数组将null作为输入。 Can someone explain this? 有人可以解释吗? Maybe something is wrong about the 3d array. 也许3d阵列出了点问题。

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. 编辑:另外,在我的情况下,第3维的值未知,因为它取决于需要首先输入的arr [0] [0] [0]的值。 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 您可以将arr初始化更改为

int arr[][][]= new int[T][4][1];

Or can create the array of the third dimension inside the inner for loop 或者可以在内部for循环内创建三维数组

for(int j = 0; j < 3; j++) {
    arr[i][j] = new int[1];
    arr[i][j][0] = sc.nextInt();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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