Question #49529

How to populate an empty two-dimensional array with random numbers from 0-5?

Expert's answer

//as we receive reference to array we don't need to returnmodified array

//real array is modified at same time

private static void fillArray(int[][] arr) {

if (arr == null) { //if someone sends anull reference

System.out.println("No input array!");

return;

}

java.util.Random random = newjava.util.Random(); //or you can import java.util.Random;

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j <arr[i].length; j++) {

arr[i][j] = random.nextInt(5); //5 if from 0 to 5 exlusively and

random.nextInt(6) if from 0 to 5 inclusively

}

}

}

//real array is modified at same time

private static void fillArray(int[][] arr) {

if (arr == null) { //if someone sends anull reference

System.out.println("No input array!");

return;

}

java.util.Random random = newjava.util.Random(); //or you can import java.util.Random;

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j <arr[i].length; j++) {

arr[i][j] = random.nextInt(5); //5 if from 0 to 5 exlusively and

random.nextInt(6) if from 0 to 5 inclusively

}

}

}

``

## Comments

## Leave a comment