Write a program in Java that creates an array of doubles. The array must have size 1000. Fill this array with random numbers between 0 and 1. Then compute and print the total value of all the elements of the array, the mean, the minimum, and the maximum.
Filling the array with random numbers must be done by a method that you define and implement. Computing and printing the statistics must be done by another method, which again you must define and implement. This second method must use an enhanced for loop.
Source code of the program and its working are given below.Comments are also given along with the code for better understanding.Screen shot of the code and output are also attached.If find any difficulty, feel free to ask in comment section. Please do upvote the answer.Thank you.
Working of the program
Source code
//importing Random class to generate random numbers import java.util.Random; public class Main { public static void main(String[] args) { //declaring an array of 1000 doubles double doubles[] = new double[1000]; //calling fillArray() method to fill array with random values double doublesFilled[] = fillArray(doubles); //calling computeStatistics() computeStatistics(doublesFilled); } public static double[] fillArray(double d[]) { //creating instance of Random class Random rand = new Random(); //iterate through array for (int i = 0; i < 1000; i++) { //generating random double value in between 0 and 1 double randomValue = rand.nextDouble(); //storing the random value into array d[i] = randomValue; } return d; } public static void computeStatistics(double arr[]) { //declaring variables double min, max, total = 0, mean; //setting min and max to arr[0] min = max = arr[0]; //iterate each double value in the array using enhanced for loop for (double i : arr) { //finding total total = total + i; //checking the element is greater than max,if yes set element as new max if (i > max) max = i; //checking the element is smaller than min,if yes set element as new min if (i < min) min = i; } //calculating mean mean = total / 1000; //printing results System.out.println("Total value: " + total); System.out.println("Mean of the elements: " + mean); System.out.println("Minimum of elements: " + min); System.out.println("Maximum of elements: " + max); } }
Screen shot of the code
Screen shot of the output
Get Answers For Free
Most questions answered within 1 hours.