0

I have a task to create three arrays of random sizes filled with random values, then create a two dimensional array and fill it with those three arrays.

I tried going for this sort of code:

int[] tab1 = new int[(int)(Math.random() * 10)];
for(int i = 0; i<tab1.length; i++){
  tab1[i] = (int)(Math.random() * 10);
}
int[] tab2 = new int[(int)(Math.random() * 10)];
for(int i = 0; i<tab2.length; i++){
  tab2[i] = (int)(Math.random() * 10);
}
int[] tab3 = new int[(int)(Math.random() * 10)];
for(int i = 0; i<tab3.length; i++){
  tab3[i] = (int)(Math.random() * 10);
}
int[][] multiTab = new int[3][];

for(int a=0; a<tab1.length; a++){
  multiTab[0][a] = tab1[a];
}
for(int b=0; b<tab2.length; b++){
  multiTab[1][b] = tab2[b];
}
for(int c=0; c<tab3.length; c++){
  multiTab[2][c] = tab3[c];
}

but the environment throws a NullPointerException, most likely because I was unable to declare the size of the second dimension of the array. How do I do this? Thanks for help in advance

AnnKont
  • 424
  • 4
  • 17
Sakkara
  • 11
  • 1

2 Answers2

0

U can do like this:

int[][] multiTab = new int[3][Math.max(tab1.length, Math.max(tab2.length, tab3.length))];

AnnKont
  • 424
  • 4
  • 17
0

You could try just putting the 1D arrays into the 2D array when you're declaring it.

For example:

        int [][] multiTab = {tab1, tab2, tab3};
Quant
  • 11
  • 1