打印具有3D阵列字段的类

时间:2016-10-06 08:00:39

标签: java arrays class

我有一个课程:

 public class CCTest {
 public double f;
 public double[][][] x;
 public double counter;
 };

我已将随机数分配给x,

    CCTest[] cls = new CCTest[5];
    for (int i = 0; i < cls.length; i++) {
    cls[i] = new CCTest();
  }

   for (int i = 0; i < (Size = 5); i++) {
   cls[i].x = new double[this.c][this.D][this.Size];
   for (int j = 0; j < this.D; j++) {
    cls[i].x = getRandomX(this.c, this.D, this.Size);
  }
 }

然后我尝试使用以下方法显示结果:

   public static void display(double[][][] array) {

    int rows = array.length;
    int columns = array[0].length;
    int depth = array[0][0].length;

    for (int d = 0; d < depth; d++) {
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                System.out.print(array[r][c][d] + " ");
            }
          System.out.println();
        }

        System.out.println();
    }
} 

随机生成方法是:

      public static double[][][] getRandomX(int x, int y, int z) {
      double[][][] result = new double[x][y][z];
      Random r = new Random();

    for (int i = 0; i < z; i++) {
        for (int j = 0; j < y; j++) {
            for (int k = 0; k < x; k++) {
                result[k][j][i] = r.nextDouble();
            }
        }
    }
    return result;
}

但输出为空[],请知道

2 个答案:

答案 0 :(得分:0)

您的display方法应该看起来像:

public static void display(double[][][] array) {
    for (int x = 0; x < array.length; x++) {
        for (int y = 0; y < array[x].length; y++) {
            for (int z = 0; z < array[x][y].length; z++) {
                System.out.println(array[x][y][z]);
            }
        }
    }
}

我想到了另一个问题。什么是getRandomX?你还没有向我们展示过。我使用以下内容:

public static double[][][] getRandom3DArray(double[][][] array) {

    Random r = new Random();
    for (int x = 0; x < array.length; x++) {
        for (int y = 0; y < array[x].length; y++) {
            for (int z = 0; z < array[x][y].length; z++) {
                array[x][y][z] = r.nextDouble();
            }
        }
    }
    return array;
}

您在显示屏中误将rowsdepth混淆。

答案 1 :(得分:0)

内部循环:for(int j = 0; j&lt; this.D; j ++){...}没用,所以你可以删除它。显示和getRandomX()函数没问题。在main中试试这个,在我的环境中工作:

    CCTest[] cls = new CCTest[5];
    for (int i = 0; i < cls.length; i++) {
        cls[i] = new CCTest();
    }

    for (int i = 0; i < (Size = 5); i++) {
        cls[i].x = new double[c][D][S];
        cls[i].x = getRandomX(c, D, S);
    }
    for (int i = 0; i < (Size = 5); i++) {
        display(cls[0].x);
    }