• Post Reply Bookmark Topic Watch Topic
  • New Topic

IndexOutOfBounds Exception  RSS feed

 
James Allen A.
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code is pretty messy at this point so my apologies, but I'm running into an IndexOutOfBounds Exception:

Here's my code. It references line 65 where I'm trying to create a loop to go through each position in ArrayList coins.

 
James Allen A.
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scratch that. I had a misunderstanding of what ArrayList.size() returns. My mistake was that I called on a position after the place where the final position in the array occurs. Hence the "out of range" exception. Got it now.
 
Tim Cooke
Marshal
Posts: 4044
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This won't work. size() is one past the last element index:




You have to subtract one:

 
Tim Cooke
Marshal
Posts: 4044
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan Jozsef Balazs wrote:This won't work. size() is one past the last element index:

Rookie mistake. Sorry about that and thanks for pointing it out. I've corrected my original post.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!