打印3D阵列

时间:2016-09-29 03:45:09

标签: java arrays loops multidimensional-array 3d

我正在尝试在填充用户给定输入之前和之后打印数组。因此,如果给定大小为3,则这将是输出:

  

//用户输入第一个矩阵的值

     

添加之前:

     

数组[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
   Array[2] =

我编写了以下代码来实现这一点(在名为ThreeDRayRunner的类中):

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]+ " ");
            }
        }
    }

但是,我收到以下错误:

  

线程“main”java.lang.NullPointerException中的异常       在ThreeDRay.print(ThreeDRay.java:13)       在ThreeDRayRunner.main(ThreeDRayRunner.java:41)

此外,在跑步者中,我要求用户输入将存储在3D阵列中的整数。要做到这一点,我要求大小并在空白时和添加给定数字后打印3D数组。这是我的代码:

Scanner keyboard = new Scanner(in);

    out.print("How many matrices are you going to enter? ");
    int s = keyboard.nextInt();


    int[][][] d3= new int [s][][];

    for(int i = 0; i < S; i++)
    {
        out.print("What is the size of the 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();
            }
        }

       out.println("The array before setting mat at spot "+i);


       ThreeDRay.print(d3);

       d3[i] = mat;


        out.println("The array after setting mat at spot "+i);

       ThreeDRay.print(d3);

1 个答案:

答案 0 :(得分:0)

您没有实例化d3的第二和第三维您是不是要在第一次打印之前执行此行?

d3[i] = mat;

所以它看起来像这样:

d3[i] = mat;

out.println("The array before setting mat at spot "+i);
ThreeDRay.print(d3);

跟进:

看起来你实际上并不想在第一次打印之前设置d3 [i]。在这种情况下,请确保d3的3个维度都是非空的,因为您的打印将打印所有这些,而不仅仅是您设置为mat的那个。在开始之前初始化第2和第3维(到0)。

int[][][] d3= new int [s][][];
for (int i=0; i < d3.length ;++i){
  d3[i] = new int[0][0];
}