Guest User

Untitled

a guest
Jun 25th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. /**
  2. This class computes the alternating sum
  3. of a set of data values.
  4. */
  5. public class DataSet
  6. {
  7. /**
  8. Constructs an empty data set.
  9. */
  10. public DataSet()
  11. {
  12. final int DATA_LENGTH = 100;
  13. data = new double[DATA_LENGTH];
  14. dataSize = 0;
  15. }
  16.  
  17. /**
  18. Adds a data value to the data set.
  19. @param x a data value
  20. */
  21. public void add(double x)
  22. {
  23. if (dataSize >= data.length)
  24. {
  25. // make a new array of twice the size
  26. double[] newData = new double[2 * data.length];
  27. // copy over all elements from data to newData
  28. System.arraycopy(data, 0, newData, 0, data.length);
  29. // abandon the old array and store in data
  30. // a reference to the new array
  31. data = newData;
  32. }
  33. data[dataSize] = x;
  34. dataSize++;
  35. }
  36.  
  37. /**
  38. Gets the alternating sum of the added data.
  39. @return sum the sum of the alternating data or 0 if no data has been added
  40. */
  41. public double alternatingSum()
  42. {
  43. . . .
  44. }
  45. private double[] data;
  46. private int dataSize;
  47. }
  48.  
  49. Use the following class as your tester class:
  50. /**
  51. This program calculates an alternating sum.
  52. */
  53. public class AlternatingSumTester
  54. {
  55. public static void main(String[] args)
  56. {
  57. DataSet data = new DataSet();
  58.  
  59. data.add(1);
  60. data.add(4);
  61. data.add(9);
  62. data.add(16);
  63. data.add(9);
  64. data.add(7);
  65. data.add(4);
  66. data.add(9);
  67. data.add(11);
  68.  
  69. double sum = data.alternatingSum();
  70. System.out.println("Alternating Sum = " + sum);
  71. System.out.println("Expected: -2");
  72. }
  73. }
Add Comment
Please, Sign In to add comment