So this is the offending bit of code:
Let's say your
coins has 2 items in it.
coins.size() will return
2 which means you're then going on to do
coins.get(2). But array indexes start at
0 which means an array with two things in it have indexes of
0 and
1 which is where your
IndexOutOfBoundsException comes from as there's no element at index
2.
Unless there's a particular reason for looping in reverse, the common syntax for a
for loop is
But if you must go in reverse then:
Or using the
foreach notation:
As an additional piece of advice. It is never a great idea to use basic numeric types for dealing with currency in an application as you'll always be at the mercy of implicit casting and rounding errors. A headache waiting to happen. Consider creating your own Money object using the
Quantity Pattern