• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array Index Out Of Bounds Exception

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Remember to always leap before you look. But always take the time to smell the tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic