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 users

Write a Java program which defines unconstrained array of user defined length n (the value of n is to be taken from a proper users 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. Here is my code so far. It would display the random numbers, but not the sum and average. I keep getting the error of "Class java.lang.ArrayIndexOutOfBoundsException"

import java.lang.*; import java.util.Scanner;

class ProjectArray {

//Method to display sum double sumArray(double[]arrayDisplay, int x) { double num=0; for(int i = 0; i < x; i++) num+=arrayDisplay[x]; return num; }

//method to display average double average (double []arrayDisplay, int x) { double num = 0; for(int i = 0; i < x; i++) num +=arrayDisplay[i]; double average = num/x; return average; }

//Method to display array void display(double[] arrayDisplay, int x) { for(int i = 0; i < x; i++) System.out.println(arrayDisplay[i]+"\t"); }

}

import java.util.Scanner; class ProjectArray2 { public static void main(String[]args) { Scanner userInput = new Scanner(System.in); System.out.println("Enter the amount of arrays"); int n = userInput.nextInt(); double[] arrayDisplay = new double[n]; ProjectArray newArray = new ProjectArray(); for(int i = 0; i < n; i ++) { double x=Math.random(); arrayDisplay[i]=x; }

newArray.display(arrayDisplay,n); double sum = newArray.sumArray(arrayDisplay, n); double avg = newArray.average(arrayDisplay, n); System.out.println ("Sum of array elements = " + sum); System.out.println("Average of array elements = "+avg); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!