Please explain this program import java.util.Random; // to generate random numbe
ID: 3833804 • Letter: P
Question
Please explain this program
import java.util.Random; // to generate random numbers
import java.util.Scanner; // to get the user input
public class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
Scanner input = new Scanner(System.in);
// ask the user for the length of an array
System.out.print("Enter the length of an array: ");
int n = input.nextInt();
// create an array of size n
int arr[] = new int[n];
/* fill in the array with n random numbers from 1 up to n */
for(int i = 0; i < n; i++)
{
arr[i] = 1 + rand.nextInt(n);
}
// (1) display all numbers of the array
System.out.println(" The random numbers stored in the array:");
for(int i = 0; i < n; i++)
{
// go to the next line after every 10 integers
if(i != 0 && i % 10 == 0)
System.out.println();
// display each integer
System.out.print(arr[i] + " ");
}
// calculate the sum of all numbers
double sum = 0;
for(int i = 0; i < n; i++)
sum += arr[i];
// (2) display the sum of all numbers
System.out.println(" The sum of " + n + " random numbers: " + sum);
// (3) calculate the average of all numbers
double average = sum / n;
// display the average of all numbers
System.out.println("The average of " + n + " random numbers: " + average);
}
}
Explanation / Answer
1. import statement is used to import packages. Here we import util package. and specifically Scanner and Random class of this package.
2. Scanner class is to take input from the user at runtime. we use nextInt() to take integer input from the user.
3. For Scanner and Random class, we have created these objects : input,rand by following commands.
Random rand = new Random();
Scanner input = new Scanner(System.in);
the new keyword is used for dynamic allocation.
4.Then we ask n from the user and create the dynamic integer array of size n.(int arr[] = new int[n])
5.Then we fill this array randomly from 1 to n. nextInt(n) method is used for this purpose.
6.Loop is run to display all number. loop run for i=1:n
7. all array elements are summed and save in total is stored in sum variable.
for(int i = 0; i < n; i++)
sum += arr[i];
8.this sum is printed on the screen.
9.At last average is calculated and shown to screen.
10.in println() ln denotes newline.