In: Computer Science
home / study / engineering / computer science / computer science questions and answers / create a new java file, containing this code public class datastatsuser { public static void ...
Your question has been answered
Let us know if you got a helpful answer. Rate this answer
Question: Create a new Java file, containing this code public class DataStatsUser { public static void...
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.
//Java code
public class DataStats { private double data[]; //Count number of elements in array private int count; //Constructor public DataStats(int N) { //create array of given size N // set up an array (to accept up to N doubles) and other member variables data = new double[N]; count =0; } //compute and return the mean of the set of numbers added so far public double mean() { double sum=0.0; for (int i = 0; i < count; i++) { sum+=data[i]; } double avg = sum/count; return avg; } /** * append number to the set; throw error if more than N numbers added * @param in */ public void append(double in) { try { if(count>data.length) throw new ArrayIndexOutOfBoundsException(); data[count] = in; count++; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Array is full now......."); } } }
//==============================================
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()); } }
//Output
//If you need any help regarding this solution .......... please leave a comment ......... thanks