Write a Java program which defines unconstrained array of user defined length n
ID: 3662432 • 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.
I saw help for this on Chegg website but mine is a little different: I need two separate classes. The first class needs method or more than one methods and be called Unit2. Make sure you call the method (s) in the test class TestUnit2.
Any help would be great. I am good at figuring out code and changing it to fill my needs but writing code from scratch I hit a road block. Thank you to anyone who can help
Explanation / Answer
import java.lang.*;
import java.util.Scanner;
class Unit2
{
void display(double[] arr, int n)
{
for(int i=0;i<n;i++)
System.out.println(arr[i]+" ");
}
double sum(double []arr, int n)
{
double sum=0;
for(int i=0;i<n;i++)
sum+=arr[i];
return sum;
}
double average (double []arr, int n)
{
double sum=0;
for( int i=0;i<n;i++)
sum+=arr[i];
double avg=sum/n;
return avg;
}
}
class TestUnit2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the value of n");
int n=sc.nextInt();
double []arr=new double[n];
Unit2 ob=new Unit2();
for(int i=0;i<n;i++){
double x=Math.random();
arr[i]=x;
}
ob.display(arr,n);
double sum=ob.sum(arr,n);
double avg=ob.average(arr,n);
System.out.println( " sum of arr elements="+sum);
System.out.println("average of arr elements="+avg);
}
}
output:
sh-4.3$ javac TestUnit2.java
sh-4.3$ java TestUnit2
enter the value of n
5
0.6510736561728845
0.5027240367119421
0.5597165880520035
0.6620236814399623
0.31869503896430773
sum of arr elements=2.6942330013411
average of arr elements=0.5388466002682201
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.