【问题标题】:How to make a random 2D jagged array of varying length?如何制作不同长度的随机二维锯齿状数组?
【发布时间】:2015-04-14 21:20:27
【问题描述】:

我必须创建一个具有随机行数 (5-10) 的二维锯齿状数组,每行具有随机长度 (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

但是,这只是随机化行和列,并不会创建锯齿状数组。任何人都可以帮助我朝着正确的方向前进吗?非常感谢!

【问题讨论】:

  • 您发布的代码导致NullPointerException,因为您没有初始化数组的第二维(您设置了rows 的数量,但没有设置@987654326 的数量@) 请记住,Java 的“二维数组”只是一个数组数组 - 参差不齐。

标签: java arrays random 2d jagged-arrays


【解决方案1】:

正如@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 

【讨论】:

    【解决方案2】:
    package JavaPrograms;
    import java.util.Random;
    public class jaggedarr
    {
        public static void main(String[] args) {
            int a[][] = new int[3][];
            Random r = new Random();
            a[0] = new int[4];
            a[1] = new int[2];
            a[2] = new int[3];
            for (int[] a1 : a)
            {
                for (int j = 0; j < a1.length; j++)
                {
                    a1[j] = r.nextInt(20);
                }
            }
            for(int i[] : a)
            {
                for(int j : i)
                {
                    System.out.print(j + " ");
                }
                System.out.println("");
            }
        }
    }
    

    【讨论】:

    • 这里,二维锯齿数组的代码......我希望这能工作......
    猜你喜欢
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多