我必须创建一个具有随机行数(5-10)的2D锯齿状数组,每行具有随机长度(5-10)。我用随机数填充了锯齿状数组。它看起来应该像这样:

2 4 1 5 3 8 6 3

2 5 8 9 7 4 3 5 6

6 7 9 3 5

2 6 7 8 4 5 3 6 7

1 4 2 2 1


这是我当前的createArray方法

 public static int [][] createArray(){
   int row = (int)(Math.random()*5)+5;
   int column = (int)(Math.random()*5)+5;

   int[][]array = new int[row][];

   for(int i = 0; i < array.length; i++){
      for(int j = 0; j < array[i].length; j++){
        //Fill the matrix with random numbers
        array[i][j] = (int)(Math.random()*10);
      }}

   return array;
  }//End createArray method


但是,这只会随机化行和列,不会创建锯齿状的数组。谁能帮助我指引正确的方向?非常感谢!

最佳答案

如@DoubleDouble所述,您的代码将引发NullPointerException

看起来您想要这样的东西:

public static int [][] createArray(){
   int row = (int)(Math.random()*5)+5;
   //int column = (int)(Math.random()*5)+5; //not needed

   int[][] array = new int[row][];

   for(int i = 0; i < array.length; i++){

      int column = (int)(Math.random()*5)+5; //create your random column count on each iteration
      array[i] = new int[column]; //Initialize with each random column count

      for(int j = 0; j < array[i].length; j++){
        //Fill the matrix with random numbers
        array[i][j] = (int)(Math.random()*10);
      }
   }

   return array;
  }//End createArray method


当然,每次运行都会产生不同的结果,但这是输出示例:

1 2 5 4 3 9 2 7 9
4 1 4 2 2 6
9 5 7 8 7 8 4 2
8 3 8 7 9 4 0
0 2 1 4 9 3 7 8
4 0 3 8 3
1 3 8 9 9 8

07-24 22:20