I am trying to build an 2D array with the size of from 1D array and pupolate it with random numbers. Why don’t I get an output when I run this code below? There is no errors in my IDE:
public void raggedArray(){
int maxRows = 3;
int maxCols = 4;
int [] onedArray = new int [maxRows];
for (int i = 0; i < maxRows; i++){
onedArray[i] = (int) ((Math.random() * 100) * maxCols);
}
int [][] twodArray = new int[maxRows][];
for (int i = 0; i < maxRows; i++){
twodArray[i] = new int[onedArray[i]];
}
for (int i = 0; i < twodArray.length; i++){
for (int j = 0; j < twodArray[i].length; j++){
twodArray[i][j] = (int) (Math.random() * 100);
}
}
System.out.println("2 - The 2D array: ");
for (int i = 0; i < twodArray.length; i++){
for (int j = 0; j < twodArray[i].length; j++){
System.out.print(twodArray[i][j] + " ");
}
System.out.println("");
}
}
}
Your code compiles correctly, runs and outputs some numbers. Maybe
raggedArray()isn’t called like Giacomo mentioned?It might also be that the two-dimensional array is created incorrectly. I suppose this:
should be replaced with: