首页 > 解决方案 > 3d 数组使用 Java.util.Scanner.nextInt() 将 null 作为输入

问题描述

以下代码在我输入数组元素时给出 NullPointerException。经过调试和分析后,我发现只有在使用 3d 数组时才会遇到异常。对于 2d,它工作正常。显然由于某种原因,该数组将 null 作为输入。有人可以解释一下吗?3d 数组可能有问题。

编辑:另外,在我的情况下,第 3 维的值是未知的,因为它取决于需要首先输入的 arr[0][0][0] 的值。所以第三维长度应该在运行时分配。

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

            }

        }
    }
}

标签: javaarraysnullpointerexception

解决方案


您尚未指定(或初始化)第三个维度。

您可以将arr初始化更改为

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

或者可以在for循环内部创建第三维数组

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

推荐阅读