• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array index out of bounds error

 
G. Graz
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.


 
Henry Wong
author
Marshal
Pie
Posts: 21185
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor 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.

Henry
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • 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.
 
vaibhav mishra
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic