The Java code below is my program that computes the average cost of an array of
ID: 3645619 • Letter: T
Question
The Java code below is my program that computes the average cost of an array of items. I understand my code I just am very confused on how the line below helps me exactly...sum = sum + shoppingList[m].cost();
Code:
public class Widget {
double averageCost (Widget[] shoppingList) {
double sum = 0.00; // Declares the
double average;
int m;
for (m=0; m <= shoppingList.length; m++)
{
sum = sum + shoppingList[m].cost();
}
average = sum/shoppingList.length;
return average;
}
private double cost() {
// Method that would return the cost of the widget
return 0;
}
}
Explanation / Answer
As per your code shoppingList[] is an array of object and here sum = sum + shoppingList[m].cost() here this statement is in loop...so value of m iterate from 0... Therefore, this will call cost() function with 0th index and add value returned by every index to sum... This is how your statement works.