Summing an array
total() adds up a cart's line items. Why does it throw on every call?
public static long total(long[] lineItemsCents) { long sum = 0; for (int i = 0; i <= lineItemsCents.length; i++) { sum += lineItemsCents[i]; } return sum;}Show answer
line 3 · Off-by-one
Valid indexes run from 0 to length - 1. With <= the loop reads index length on its last pass and throws ArrayIndexOutOfBoundsException.
for (int i = 0; i < lineItemsCents.length; i++) {Interview follow-up: An enhanced for loop (for (long c : lineItemsCents)) removes the index, and the bug, entirely.