java - How to make a random 2D jagged array of varying length? -
i have create 2d jagged array random number of rows (5-10) each row having random length (5-10). filled jagged array random numbers. should this:
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
this current createarray
method
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 = 0; < array.length; i++){ for(int j = 0; j < array[i].length; j++){ //fill matrix random numbers array[i][j] = (int)(math.random()*10); }} return array; }//end createarray method
however, randomizes rows , columns , doesn't create jagged array. can lead me in right direction? lot!
as @doubledouble stated, code throws nullpointerexception
.
it looks want this:
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 = 0; < array.length; i++){ int column = (int)(math.random()*5)+5; //create random column count on each iteration array[i] = new int[column]; //initialize each random column count for(int j = 0; j < array[i].length; j++){ //fill matrix random numbers array[i][j] = (int)(math.random()*10); } } return array; }//end createarray method
of course produce different results each time runs, here sample of output:
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
Comments
Post a Comment