Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger
  • Frits Walraven

Array index out of bounds error

Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting an "java.lang.ArrayIndexOutOfBoundsException" error in the code below I think it might be at sum = average[i]; but I do not see why I am throwing that error ? The array element has an index of 16 , reading off a .txt file . Ok, please let me know if you can see what I am doing incorrectly ? Thank you.

Posts: 23874
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Besides the file, method, and line number, the exception also tells you which index was being referrenced. It would help if you give us the stacktrace -- at least the fist few lines of it.

Posts: 69019
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to check the format of a for loop when iterating an array. Unfortunately there isn't a good example in the Java Tutorials; you should find something in your textbook. Look at the binary operators very carefully.
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
assuming that you have 16 elements for input here is what you did wrong

consider this line

you declare a string array with 16 elements , the index being 0 to 15( 15(1st to 15th index ) + 1(0th index ) )
it takes elements from intFile(1st element at 0th index ... 4th element at 3rd index and 16th element at 15th index)
so avarage[15] infact represents your 16th element(15 is the index here)

in the following array iteration for loop at this line

the <= makes it iterate from 'zero' to 16 th (i.e., your array should have 17 elements)
so just remove '=' sign and change line to

Note: maxList.size() return 16 because you array has 16 elements indexed from 'zero' to 15
I am Arthur, King of the Britons. And this is a tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
    Bookmark Topic Watch Topic
  • New Topic