Java Array Traversal Logic
The following method is intended to calculate the total price of all items in a shopping cart, which is represented by an array of Item objects.
/** Returns the total price of all items in the cart.
* Precondition: The cart array has been initialized.
*/
public static double totalPrice(Item[] cart) {
/* method body */
}
Which of the following code segments, when substituted for /* method body */, will cause the method to function correctly?
I.
double total = 0;
for (int i = 0; i <= cart.length; i++)
total += cart[i].getPrice();
return total;
II.
double total = 0;
for (Item item : cart)
total += item.getPrice();
return total;
III.
double total = cart[0].getPrice();
for (int i = 1; i < cart.length; i++)
total += cart[i].getPrice();
return total;
A
II and III only
B
I only
C
I and III only
D
II only
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 1 | 2 | 0m 00s | 90 |
| #2 | singhris000 | 1 | 1 | 1m 43s | -3 |
| #3 | bommasam000 | 0 | 3 | 6m 22s | -412 |
| #4 | y.seong2027 | 1 | 4 | 34m 13s | -1,983 |
Items per page:
10
1 – 4 of 4
APFIVE