In: Computer Science
Create a new Java file, containing this code
public class DataStatsUser { public static void main (String[] args) { DataStats d = new DataStats(6); d.append(1.1); d.append(2.1); d.append(3.1); System.out.println("final so far is: " + d.mean()); d.append(4.1); d.append(5.1); d.append(6.1); System.out.println("final mean is: " + d.mean()); } }
This code depends on a class called DataStats, with the following API:
public class DataStats { public DataStats(int N) { } // set up an array (to accept up to N doubles) and other member variables public double mean() { return 0; } //compute and return the mean of the set of numbers added so far public void append(double in) { } //append number to the set; throw error if more than N numbers added }
Your job: implement DataStats, so that it correctly works when used by DataStatsUser.
Below is the solution:
import java.util.ArrayList;
public class DataStatsUser {
public static void main(String[] args) {
DataStats d = new
DataStats(6);
d.append(1.1);
d.append(2.1);
d.append(3.1);
System.out.println("final so far
is: " + d.mean());
d.append(4.1);
d.append(5.1);
d.append(6.1);
System.out.println("final mean is:
" + d.mean());
}
}
public class DataStats {
ArrayList<Double> arrlist; //declare
arraylist
public DataStats(int N) {
arrlist = new
ArrayList<Double>(N); //declare the size of arraylist
}
// set up an array (to accept up to N doubles) and
other member variables
public double mean() {
int sum = 0, i;
for (i = 0; i < arrlist.size();
i++) { //iterate through loop
sum +=
arrlist.get(i); //sum of all the arraylist
}
double mean = (float)sum /
arrlist.size(); //calculate the mean
return mean;
}
// compute and return the mean of the set of
numbers added so far
public void append(double in) {
arrlist.add(in); //append the
arraylist
}
// append number to the set; throw error if more than
N numbers added
}
sample output:
final so far is: 2.0
final mean is: 3.5