Pearl Pearl - 17 days ago 6
Java Question

How to create a sum of alternating integers from an int array?

I am supposed to compute the alternating sum of all elements in an array. For example, the array with values 1 4 9 16 9 7 4 9 11 should compute


1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = -2


following code was provided by instructor

public static void main(String[] args)
{
double[] data = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
AlternatingSum util = new AlternatingSum();
double total = util.alternatingSum(data);
System.out.println("Expected sum: -2");
System.out.println("Alternating sum: " + total);
}


What does util.alternatingSum(data) mean? Do I have to create an alternatingSum method? And if so, what is the heading code for that method?

Thank you for any help.

Answer

What does util.alternatingSum(data) mean?

It calls alternatingSum(double[]) method of AlternatingSum class. util is an object of AlternatingSum class, which is used to call this method.

Do I have to create an alternatingSum method?

If the code is not there, this code will not compile!

You need to have an AlternatingSum class, inside which you'd have an alternatingSum() method.

So, YES, you need to have that code for this code to compile and execute successfully.

And if so, what is the heading code for that method?

The method header should go as:

double alternatingSum(double[])
{
  // your code goes here.
}

as this method accepts an array of doubles, and returns a double value.