You should create methods to do it in a modular way. Other improvement you can do is to use Random::nextInt
to get rid of multiplying and casting. Given below is a sample program:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int r = input.nextInt();
int[] list = new int[r];
init(list);
print(list);
}
static void init(int list[]) {
Random random = new Random();
for (int i = 0; i < list.length; i++) {
list[i] = random.nextInt(50) + 1;
}
}
static void print(int list[]) {
for (int i : list) {
System.out.print(i + " ");
}
}
}
A sample run:
Enter the size of the array: 3
4 1 38
[Update] Posting the following code to answer OP's requirement (mentioned in the comment below) of also sorting the elements:
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int r = input.nextInt();
int[] list = new int[r];
init(list);
System.out.println("Original list:");
print(list);
System.out.println("\nSorted list:");
Arrays.sort(list);
print(list);
}
static void init(int list[]) {
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int n = (int) (Math.random() * 50 + 1);
list[i] = random.nextInt(50) + 1;
}
}
static void print(int list[]) {
for (int i : list) {
System.out.print(i + " ");
}
}
}
A sample run:
Enter the size of the array: 3
Original list:
27 5 37
Sorted list:
5 27 37