In: Computer Science
Write a class DataSet that stores a number of values of type
double in an array list. Provide methods to insert a value to the
array list and to compute the sum,
average, and maximum value.
Please put a note on what you did is for what. So I can understand this question better.
Code provided:
import java.util.*;
public class DataSet
{
private ArrayList<Double> data;
/**
Constructs an empty data set.
@param maximumNumberOfValues the maximum this data set can
hold
*/
public DataSet()
{
data = new ArrayList<Double>();
}
/**
Adds a data value to the data set if there is a room in the
array.
@param value a data value
*/
public void add(double value)
{
// COMPLETE THIS METHOD
}
/**
Gets the sum of the added data.
@return sum of the data or 0 if no data has been added
*/
public double getSum()
{
// COMPLETE THIS METHOD
}
/**
Gets the average of the added data.
@return average of the data or 0 if no data has been added
*/
public double getAverage()
{
// COMPLETE THIS METHOD
}
/**
Gets the maximum value entered.
@return maximum value of the data
NOTE: returns -Double.MAX_VALUE if no values are entered.
*/
public double getMaximum()
{
// COMPLETE THIS METHOD
}
}
/*DataSet.java*/
import java.util.*;
public class DataSet
{
private ArrayList<Double> data;
/**
Constructs an empty data set.
@param maximumNumberOfValues the maximum this data set can
hold
*/
public DataSet()
{
data = new ArrayList<Double>();
}
/**
Adds a data value to the data set if there is a room in the
array.
@param value a data value
*/
public void add(double value)
{
data.add(value); // add value to arraylist
}
/**
Gets the sum of the added data.
@return sum of the data or 0 if no data has been added
*/
public double getSum()
{
double sum = 0.0;
if(data.size() < 0) return 0; // 0 if no data has been
added
for (int i = 0; i < data.size(); i++) {//run until array list
size
sum+=data.get(i); // calc sum
}
return sum;
}
/**
Gets the average of the added data.
@return average of the data or 0 if no data has been added
*/
public double getAverage()
{
if(data.size() < 0)return 0;//0 if no data has been added
return getSum()/data.size();// find avg
}
/**
Gets the maximum value entered.
@return maximum value of the data
NOTE: returns -Double.MAX_VALUE if no values are entered.
*/
public double getMaximum()
{
double max = data.get(0);
if(data.size() < 0){ //Double.MAX_VALUE if no data has been
added
return Double.MAX_VALUE;
}
for (int i = 0; i < data.size(); i++) {
if(max < data.get(i)){
max = data.get(i); // assign max element to max
}
}
return max;
}
}
/*Driver class */
/* Main.java*/
public class Main {
public static void main(String[] args) {
DataSet obj = new DataSet();
for (int i = 0; i < 5; i++) {
obj.add((i+1));
}
System.out.println("Sum: "+obj.getSum());
System.out.println("Average: "+obj.getAverage());
System.out.println("Maximum: "+obj.getMaximum());
}
}