首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何制作不同长度的随机2D锯齿数组?

如何制作不同长度的随机2D锯齿数组?
EN

Stack Overflow用户
提问于 2015-04-15 05:20:28
回答 2查看 1.6K关注 0票数 0

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

代码语言:javascript
复制
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方法

代码语言:javascript
复制
 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

但是,这只是随机化了行和列,并不会创建锯齿数组。有人能帮我把方向引向正确的方向吗?非常感谢!

EN

回答 2

Stack Overflow用户

发布于 2015-04-15 05:36:39

正如@DoubleDouble所述,您的代码抛出了一个NullPointerException

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

代码语言:javascript
复制
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

当然,它每次运行时都会产生不同的结果,但以下是它将输出的结果示例:

代码语言:javascript
复制
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 
票数 1
EN

Stack Overflow用户

发布于 2020-02-18 18:26:08

代码语言:javascript
复制
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("");
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29637606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档