Need to convert ArrayAverage to use ArrayLists instead of arrays. Nmae your clas
ID: 3568918 • Letter: N
Question
Need to convert ArrayAverage to use ArrayLists instead of arrays. Nmae your class ArrayListAverage, which shall contain the method described below.
COMPUTEAVERAGE
keep the same method name: computeAverage. Change computeAverage to compute the average of items in an ArrayList instead of an array. Keep other types the same.
MAIN
in main, instead of using a fixed number of elements, use the Scanner method, hasNextInt to read intergers until there are no more. Change the array numbers to be an ArrayList of Interger. The code that calls computeAverage and prints the result should remaind the same.
Here is the code that needs to be change.
Explanation / Answer
Here you go :)
//Reads input until a non integer value is entered.
//ArrayListAverage class
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListAverage {
/**
* Computes the average of the int's in array numbers
* @param numbers array of int's
* @return average of the int's in array numbers
*/
public static double computeAverage(ArrayList<Integer> numbers) {
double average, sum = 0;
// Initialize sum
sum = 0;
// Find the sum of integers in array
for (int i = 0; i < numbers.size(); ++i)
sum += numbers.get(i);
average = sum / numbers.size(); // Compute average
return average;
}
public static void main(String[] args) {
ArrayList<Integer> numbers=new ArrayList<Integer>();
double average;
Scanner input = new Scanner(System.in);
while(input.hasNextInt()) numbers.add(input.nextInt());
average = computeAverage(numbers);
// Emit average
System.out.printf("%.2f ", average);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.