java - 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
}
}
}
}
解决方案
您尚未指定(或初始化)第三个维度。
您可以将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();
}
推荐阅读
- google-apps-script - Google 日历 ID 授权/配置
- javascript - How to split moment dates into array from time slot?
- azure-data-factory - ADF - 在复制数据流中使用循环中的参数
- powerbi - 搜索特定单词并将其提取到 Power BI DAX 中的新列中
- postgresql - 如何在 PostgreSQL 中将 DEFAULT 插入到准备好的语句中
- php - PHP 代码 - 将二维数组转换为一维数组 $vector - 函数 toVector 和 toArray - 怎么做?
- java - 如何解决ID无法恢复实体的问题?
- scala - 使用 JsonFile 中的值创建对象
- python - Python数据框:计算所有列的平均值/差异/总和/ ...
- c# - 如何按ID显示或获取访问数据库的所有名称