我正在尝试打印3D数组。这是我的代码:
public static void print(int [][][] array)
{
for (int i=0; i<array.length; i++ )
{
for (int x=0; x<array[i].length;x++)
{
System.out.println();
System.out.print("row "+ x);
for (int j=0; j<array[i][x].length;j++)
{
System.out.print (array[i][x][j]+ " ");
}
}
}
我做错了什么吗? 我每次打电话
ThreeDRay.print(d3);
我收到此错误:
在ThreeDRay.print(ThreeDRay.java:13)处的线程“main”java.lang.NullPointerException中的异常 ThreeDRayRunner.main(ThreeDRayRunner.java:54)
其余代码是:
public static void main( String args[] )
{
Scanner keyboard = new Scanner(in);
out.print("How many matrices do you wish to enter? :: ");
int matCnt = keyboard.nextInt();
//instantiate a ThreeDRay
int[][][] d3= new int [matCnt][][];
for (int x=0; x < d3.length ;++x){
d3[x] = new int[0][0];
for(int i = 0; i < matCnt; i++)
{
out.print("What is the size of matrix " + i + " : ");
int size = keyboard.nextInt();
int[][] mat = new int[size][size];
out.println();
for(int r=0; r<mat.length; r++)
{
for(int c=0; c<mat[r].length; c++)
{
out.print("Enter a value for spot " + r + " - " + c + " :: ");
mat[r][c]=keyboard.nextInt();
}
}
if (i==0 && i<matCnt)
{
for (int l=0; l<=matCnt; l++){
out.println("\nThreeDRay before setting mat at spot "+l);
}
}
ThreeDRay.print(d3);
d3[i] = mat;
out.println("\nThreeDRay after setting mat at spot "+i);
ThreeDRay.print(d3);
我必须说明我是如何填充矩阵的
//user inputs values for first matrix
添加之前:
数组[0] =
数组[1] =
数组[2] =
//添加用户输入
添加后:
数组[0] =第0行= [...]
row 1 = [...] ... depending on user given size of the first matrix Array[1] = Array[2] =
//要求输入第二个矩阵
添加前
数组[0] =第0行= [...]
row 1 = [...] ... depending on user given size of the first matrix Array[1] = Array[2] =
添加
后数组[0] =第0行= [...]
row 1 = [...] ... depending on user given size of the first matrix
数组[1] =第0行= [...]
row 1 = [...] ... depending on user given size of the first matrix
数组[2] =
答案 0 :(得分:0)
你需要在这个for循环中关闭花括号:
for (int x = 0; x < d3.length; ++x) {
d3[x] = new int[0][0];
}
如果没有右括号,你的程序只会初始化d3
中的一个元素,而剩余的元素仍然为空时继续进入下一个for循环,当你尝试打印整个元素时,它会给出NullPointerException
d3
正在进行中。