Reputation: 1
I have to create a 2D jagged array with a random number of rows (5-10) with each row having a random length (5-10). I filled the jagged array with random numbers. It should look something like 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 is my 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 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
However, this just randomizes the rows and columns and doesn't create a jagged array. Can anyone help lead me in the right direction? Thanks a lot!
Upvotes: 0
Views: 1970
Reputation: 1
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("");
}
}
}
Upvotes: 0
Reputation: 43322
As @DoubleDouble stated, your code throws a NullPointerException
.
It looks like you want something like 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 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
Of course it will produce different results each time it runs, but here is a sample of what it will 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
Upvotes: 1