wood burning stoves*
The moose likes Java in General and the fly likes Array Index Out Of Bounds Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Array Index Out Of Bounds Exception" Watch "Array Index Out Of Bounds Exception" New topic
Author

Array Index Out Of Bounds Exception

Cary Tanner
Greenhorn

Joined: Feb 08, 2005
Posts: 4
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

Joined: Dec 29, 2004
Posts: 1071
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

Joined: Feb 08, 2005
Posts: 4
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

Joined: Aug 08, 2003
Posts: 326
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)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Array Index Out Of Bounds Exception