I am trying to print a 3D Array. This is my code:
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]+ " ");
}
}
}
Is there something am I doing wrong? Every time I call
ThreeDRay.print(d3);
I get this error:
Exception in thread "main" java.lang.NullPointerException at ThreeDRay.print(ThreeDRay.java:13) at ThreeDRayRunner.main(ThreeDRayRunner.java:54)
The rest of the code is this:
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);
I have to show how I filled the matrices
//user inputs values for first matrix
Before adding:
Array [0] =
Array [1] =
Array [2] =
//add user inputs
After adding:
Array [0] = row 0 = [...]
row 1 = [...] ... depending on user given size of the first matrix Array[1] = Array[2] =
//ask for inputs for second matrix
Before Adding
Array [0] = row 0 = [...]
row 1 = [...] ... depending on user given size of the first matrix Array[1] = Array[2] =
After adding
Array [0] = row 0 = [...]
row 1 = [...] ... depending on user given size of the first matrix
Array[1] = row 0 = [...]
row 1 = [...] ... depending on user given size of the first matrix
Array[2] =
You need to close the curly brace in this for loop:
for (int x = 0; x < d3.length; ++x) {
d3[x] = new int[0][0];
}
Without the closing brace, your program continues into the next for loop after having initialized only one element of d3
while remaining elements are still null, which gives a NullPointerException
when you try to print the entire d3
underway.
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.