30,152 views
20 votes
20 votes
Array Basics pls help

Array Basics pls help-example-1
User Cmbarbu
by
3.2k points

1 Answer

21 votes
21 votes

Answer:

import java.util.Random;

class Main {

static int[] createRandomArray(int nrElements) {

Random rd = new Random();

int[] arr = new int[nrElements];

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

arr[i] = rd.nextInt(1000);

}

return arr;

}

static void printArray(int[] arr) {

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

System.out.println(arr[i]);

}

}

public static void main(String[] args) {

int[] arr = createRandomArray(5);

printArray(arr);

}

}

Step-by-step explanation:

I've separated the array creation and print loop into separate class methods. They are marked as static, so you don't have to instantiate an object of this class type.

User Gladys
by
3.2k points