Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Index Out Of Bounds Exception

 
Cary Tanner
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm getting and error when I try to run this program





Here's what I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at java146.project1.ProcessOrders.writeOutput(ProcessOrders.java:135)
at java146.project1.ProcessOrders.run(ProcessOrders.java:29)
at java146.project1.OrderDriver.main(OrderDriver.java:22)


I don't understand why this is happening.
[ February 08, 2005: Message edited by: Cary Tanner ]
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your orders Array is only of size 4. Why the magic number 5 in the writeOutput for loop? It should be i < orders.length.
 
Cary Tanner
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Silly me, that's what I did at first but I guess I wrote "i <= orders.length", and the equals is what screwed me up. Thanks!
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ArrayIndexOutOfBoundException indicates you have asked for an element of the array that doesn't exist.

If your array was:
int[] array = {1,2,3};
and you asked for array[3], you would get this exception. (remember, Java arrays are zero based, so array[3] would refer to the 4th element, if it existed)

That said, it is always better to use the length of the array to control a for when iterating through an array, as so:

for( int i = 0; i < array.length; ++i )

this way, you can't overrun the array because the array size itself is controlling the loop.

In your case, you need to fix line 135 in your program (as per the error message)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic