This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
posted
0
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
posted
0
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!
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)
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.