Write a program that reads a sequence of integers into an array and that computes the alternating sum of all elements in the array. For example, if the program is executed with the input data
then it computes
Use the following class in your solution:
/**
This class computes the alternating sum
of a set of data values.
*/
public class DataSet
{
/**
Constructs an empty data set.
*/
public DataSet()
{
final int DATA_LENGTH = 100;
data = new double[DATA_LENGTH];
dataSize = 0;
}
/**
Adds a data value to the data set.
@param x a data value
*/
public void add(double x)
{
if (dataSize >= data.length)
{
// make a new array of twice the size
double[] newData = new double[2 * data.length];
// copy over all elements from data to newData
System.arraycopy(data, 0, newData, 0, data.length);
// abandon the old array and store in data
// a reference to the new array
data = newData;
}
data[dataSize] = x;
dataSize++;
}
/**
Gets the alternating sum of the added data.
@return sum the sum of the alternating data or 0 if no data has been added
*/
public double alternatingSum()
{
. . .
}
private double[] data;
private int dataSize;
}
Use the following class as your tester class:
/**
This program calculates an alternating sum.
*/
public class AlternatingSumTester
{
public static void main(String[] args)
{
DataSet data = new DataSet();
data.add(1);
data.add(4);
data.add(9);
data.add(16);
data.add(9);
data.add(7);
data.add(4);
data.add(9);
data.add(11);
double sum = data.alternatingSum();
System.out.println("Alternating Sum = " + sum);
System.out.println("Expected: -2");
}
}
2 comments:
What is the " . . ." After the public double alternatingSum(); ?
That's where the missing code that you have to fill in is.
Post a Comment