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();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.