Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
I am trying to 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
 
1 4 9 16 9 7 4 9 11
then it computes
 
1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = - 2
 
I have below code so far:
 
import java.util.Arrays;
 
/**
   This class computes the alternating sum
   of a set of data values.
*/
public class DataSet
{
   private double[] data;
   private int dataSize;
 
   /**
      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)
         data = Arrays.copyOf(data, 2 * data.length);
      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()
   {
      . . .
   }
}
 
I have to use the following class as the 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.0");
   }
}
Posted 6-Apr-12 20:04pm
Edited 6-Apr-12 23:00pm
JF201553.6K
v3

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.
 
Try it yourself, you may find it is not as difficult as you think!
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.150326.1 | Last Updated 7 Apr 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100