Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Java program which defines unconstrained array of user defined length n

ID: 3675924 • Letter: W

Question

Write a Java program which defines unconstrained array of user defined length n (the value of n is to be taken from a proper user’s input). Fill in the array with n random numbers. The application should (1) display all elements of the array, (2) display the sum of all elements, and (3) calculate the average of all elements.
Random numbers need to be generated inside the program making use of the prebuilt Java Random numbers generator available in the Math library class.

Create two classes as follows:

public class Unit2DQ2

    {

              get the user input for the array length

              declare your array (int or double)

              fill the array with random integers (or doubles)

              find the sum of all the elements

              calculate the average of all elements

              display the size of the array

              display the sum of elements of the array

              display the aveerage of all elements of the array

    }

Save this class in a file called 'Unit2DQ2.java'.

public class TestUnit2DQ2

              {

                             Unit2DQ2 dq2 = new Unit2DQ2();

                              call your method(s); //dq2.methodName() etc..

              }

Explanation / Answer


import java.util.*;

public class Unit2DQ2 {

void print()
{
Scanner input = new Scanner(System.in);
  
System.out.print("Enter the length of array: ");
int length = input.nextInt();
Double[] numbers = new Double[length];
System.out.println("Size of array is :"+length);
Double sum = 0.0;
Random randomGenerator = new Random();
for (int i =0; i < length ;i++ ) {
Double randomInt = randomGenerator.nextDouble();
numbers[i] = randomInt;
sum = sum + numbers[i];
System.out.println("number["+i+"] "+numbers[i]);
}

Double average = sum/ length;
System.out.println("Sum of elements of array: "+sum);
System.out.println("Average: "+average);

}
}

public class TestUnit2DQ2 {
   public static void main(String [] arg){
Unit2DQ2 dq2 = new Unit2DQ2();
dq2.print();
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote